prettier、eslint、stylelint在项目中使用

发布于:2025-09-02 ⋅ 阅读:(21) ⋅ 点赞:(0)
  1. prettier
    1)vscode中使用
    a. 安装插件(Prettier)

在这里插入图片描述
安装成功后,在你打开支持的文件时,下方文件信息状态栏会有prettier标致:
在这里插入图片描述
双击它或者直接在输出命令窗口那里查看prettier的日志信息:
在这里插入图片描述
从日志这里可以看出,它是优先使用项目中的prettier配置的。
另外,一般你下载代码格式化插件,都是搭配vscode的文件自动保存格式的(这样方便),但是注意,这个自动保存格式化使用的是文件的默认格式化配置。

b. vscode配置
格式化的默认配置修改为prettier。
在这里插入图片描述
开启格式化自动保存。
在这里插入图片描述
最后记得要重启vscode

注意:当配置发生变化的时候也要重启vscode

2)项目中使用
a. 新建配置(.prettierrc.cjs 或者.prettier.json),下面以.prettierrc.cjs为例

module.exports = {
        printWidth: 150, // 每行代码长度(默认80)
        tabWidth: 2, // 缩进空格数
        useTabs: false, //不用tab缩进
        semi: true, //// 在语句末尾打印分号
        singleQuote: true, // 使用单引号而不是双引号
        vueIndentScriptAndStyle: true, //Vue文件脚本和样式标签缩进
        quoteProps: 'as-needed', // 更改引用对象属性的时间 可选值"<as-needed|consistent|preserve>"
        jsxSingleQuote: true, // 在JSX中使用单引号而不是双引号
        trailingComma: 'es5', //多行时尽可能打印尾随逗号。(例如,单行数组永远不会出现逗号结尾。) 可选值"<none|es5|all>",默认none
        bracketSpacing: true, // 在对象文字中的括号之间打印空格
        jsxBracketSameLine: false, //jsx 标签的反尖括号需要换行
        arrowParens: 'always', // 在单独的箭头函数参数周围包括括号 always:(x) => x \ avoid:x => x
        rangeStart: 0, // 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码
        rangeEnd: Infinity,
        requirePragma: false, // 指定要使用的解析器,不需要写文件开头的 @prettier
        insertPragma: false, // 不需要自动在文件开头插入 @prettier
        proseWrap: 'preserve', // 使用默认的折行标准 always\never\preserve
        htmlWhitespaceSensitivity: 'css', // 指定HTML文件的全局空格敏感度 css\strict\ignore
        endOfLine: 'auto', // 因为prettier的规范和eslint的换行规则不同,所以这个必须配置。要不然每次打开文件都会有一堆的警告;换行符使用 lf 结尾是 可选值"<auto|lf|crlf|cr
};

b. package.json增加配置

"lint:prettier": "prettier --write \"src/**/*.{js,ts,json,tsx,css,scss,vue,html,md}\""

在这里插入图片描述
c. 执行 npm run lint:prettier

  1. eslint
    eslint:https://eslint.org/
    @antfu/eslint-config:https://www.npmjs.com/package/@antfu/eslint-config
    1)安装eslint插件
    在这里插入图片描述

2)通过生成配置文件

npx @antfu/eslint-config@latest

在这里插入图片描述
3)安装

npm install @antfu/eslint-config@latest

4)更改eslint.config.js

import antfu from '@antfu/eslint-config'

export default antfu({
  // @stylistic/eslint-plugin-plus
  // stylistic: true,
  stylistic: {
    indent: 2, // 4, or 'tab'
    quotes: "single", // or 'double/single'
    semi: true,
  },
  // eslint-plugin-format
  formatters: true,
  // unocss 检测&格式化 暂时注释 等配置了unocss再开放为true
  // unocss: true,
  // vue的eslint配置
  vue: true,
  // 保存删除未引入的代码
  // isInEditor: false,
  // 9x版本 忽略文件这种配置方式 废弃掉eslintignore
  ignores: [
    '*.sh',
    'node_modules',
    '*.md',
    '*.woff',
    '*.ttf',
    '.idea',
    '/public',
    '/docs',
    '.husky',
    '.local',
    '/bin',
    'Dockerfile',
  ],
  lessOpinionated: true,
  rules: {
    'eslint-comments/no-unlimited-disable': 'off',
    'ts/no-use-before-define': 'off',
    'style/no-mixed-operators': 'off',
    'no-console': 'warn',
    'ts/no-unused-expressions': 'off',
    'style/max-statements-per-line': 'off',
    'ts/prefer-namespace-keyword': 'off',
    'antfu/top-level-function': 'off',
    'node/prefer-global/process': 'off',
    'ts/consistent-type-definitions': 'off',
    'ts/ban-ts-comment': 'off',
    'vue/singleline-html-element-content-newline': 'off', // vue 标签强制换行
    // 关闭一些耗时的规则
    'import/no-cycle': 'off',
    'import/no-deprecated': 'off',
    'import/no-named-as-default': 'off',
    'prefer-promise-reject-errors': 'off',
    'perfectionist/sort-imports': [
      'error',
      {
        type: 'unsorted',
      },
    ],
    // 'ts/no-unused-vars': ['error', {
    //   argsIgnorePattern: '^_',
    //   varsIgnorePattern: '^_',
    // }],
    // '@typescript-eslint/no-unused-vars': ['error', {
    //   argsIgnorePattern: '^_',
    //   varsIgnorePattern: '^_',
    // }],
  },
})

5)安装依赖

 pnpm install
  1. 重启vscode
    7)效果展示
    在这里插入图片描述
  1. stylelint
    官网:https://stylelint.io/user-guide/rules/
    1)安装插件
    在这里插入图片描述
    2)安装依赖包
npm install -D stylelint stylelint-config-standard stylelint-order stylelint-config-prettier

npm install -D less less-loader stylelint stylelint-config-standard stylelint-config-standard-less stylelint-config-recommended stylelint-config-recommended-less stylelint-config-recommended-vue stylelint-less stylelint-prettier stylelint-order @stylistic/stylelint-plugin
stylelint-config-recommended-scss stylelint-config-standard-scss

3)增加以下配置
.stylelintignore
```bash
/dist/*
/public/*
public/*

.stylelintrc.cjs

module.exports = {
  root: true,
  plugins: ['stylelint-order'],
  extends: ['stylelint-config-standard', 'stylelint-config-prettier'],
  rules: {
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['global'],
      },
    ],
    'selector-pseudo-element-no-unknown': [
      true,
      {
        ignorePseudoElements: ['v-deep'],
      },
    ],
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: [
          'tailwind',
          'apply',
          'variants',
          'responsive',
          'screen',
          'function',
          'if',
          'each',
          'include',
          'mixin',
        ],
      },
    ],
    'no-empty-source': null,
    'named-grid-areas-no-invalid': null,
    'unicode-bom': 'never',
    'no-descending-specificity': null,
    'font-family-no-missing-generic-family-keyword': null,
    'declaration-colon-space-after': 'always-single-line',
    'declaration-colon-space-before': 'never',
    // 'declaration-block-trailing-semicolon': 'always',
    'rule-empty-line-before': [
      'always',
      {
        ignore: ['after-comment', 'first-nested'],
      },
    ],
    'unit-no-unknown': [true, { ignoreUnits: ['rpx'] }],
    'order/order': [
      [
        'dollar-variables',
        'custom-properties',
        'at-rules',
        'declarations',
        {
          type: 'at-rule',
          name: 'supports',
        },
        {
          type: 'at-rule',
          name: 'media',
        },
        'rules',
      ],
      { severity: 'warning' },
    ],
  },
  ignoreFiles: ['**/*.js', '**/*.jsx', '**/*.tsx', '**/*.ts'],
};

stylelint.config.js(16.x.x.x以上)

export default {
  plugins: ['stylelint-order'],
  extends: ['stylelint-config-standard', 'stylelint-config-prettier'],
  rules: {
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['global'],
      },
    ],
    'selector-pseudo-element-no-unknown': [
      true,
      {
        ignorePseudoElements: ['v-deep'],
      },
    ],
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: [
          'tailwind',
          'apply',
          'variants',
          'responsive',
          'screen',
          'function',
          'if',
          'each',
          'include',
          'mixin',
        ],
      },
    ],
    'no-empty-source': null,
    'named-grid-areas-no-invalid': null,
    'unicode-bom': 'never',
    'no-descending-specificity': null,
    'font-family-no-missing-generic-family-keyword': null,
    'declaration-colon-space-after': 'always-single-line',
    'declaration-colon-space-before': 'never',
    // 'declaration-block-trailing-semicolon': 'always',
    'rule-empty-line-before': [
      'always',
      {
        ignore: ['after-comment', 'first-nested'],
      },
    ],
    'unit-no-unknown': [true, { ignoreUnits: ['rpx'] }],
    'order/order': [
      [
        'dollar-variables',
        'custom-properties',
        'at-rules',
        'declarations',
        {
          type: 'at-rule',
          name: 'supports',
        },
        {
          type: 'at-rule',
          name: 'media',
        },
        'rules',
      ],
      { severity: 'warning' },
    ],
  },
  ignoreFiles: ['**/*.js', '**/*.jsx', '**/*.tsx', '**/*.ts', '/dist/*', '/public/*', 'public/*'],
}

stylelint.config.mjs


export default {
  root: true,
  plugins: ['stylelint-prettier', 'stylelint-less', '@stylistic/stylelint-plugin'],
  extends: ['stylelint-config-standard', 'stylelint-config-standard-less'],
  ignoreFiles: ['**/*.js', '**/*.jsx', '**/*.tsx', '**/*.ts'],
  overrides: [
    {
      files: ['*.(html|vue)', '**/*.(html|vue)'],
      customSyntax: 'postcss-html',
      extends: ['stylelint-config-recommended-vue'],
      rules: {
        'selector-pseudo-class-no-unknown': [
          true,
          {
            ignorePseudoClasses: ['global', 'deep'],
          },
        ],
        'selector-pseudo-element-no-unknown': [
          true,
          {
            ignorePseudoElements: ['v-deep', 'v-global', 'v-slotted'],
          },
        ],
      },
    },
    {
      files: ['*.less', '**/*.less'],
      customSyntax: 'postcss-less',
      extends: ['stylelint-config-recommended-less'],
    },
    {
      files: ['*.scss', '**/*.scss'],
      customSyntax: 'postcss-scss',
      extends: ['stylelint-config-recommended-scss', 'stylelint-config-recommended-vue/scss'],
    },
  ],
  rules: {
    'prettier/prettier': [
      true,
      {
        preferPositionShorthand: 'never',
        preferOverflowShorthand: 'separate',
      },
    ],
    'media-feature-range-notation': null,
    'selector-not-notation': null,
    'import-notation': null,
    'function-no-unknown': null,
    'selector-class-pattern': null,
    'at-rule-prelude-no-invalid': null,
    'declaration-property-value-no-unknown': null,
    'declaration-property-value-keyword-no-deprecated': null,
    'declaration-property-value-disallowed-list': {
      inset: [/.*/], // 禁止所有 inset 属性值
    },
    // 允许使用传统属性
    'declaration-property-value-allowed-list': {
      top: [/.*/],
      right: [/.*/],
      bottom: [/.*/],
      left: [/.*/],
    },
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['global', 'deep'],
      },
    ],
    'selector-pseudo-element-no-unknown': [
      true,
      {
        ignorePseudoElements: ['v-deep'],
      },
    ],
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: [
          'extends',
          'ignores',
          'include',
          'mixin',
          'if',
          'else',
          'media',
          'for',
          'at-root',
          'unocss',
          'apply',
          'variants',
          'responsive',
          'screen',
          'function',
          'each',
          'use',
          'forward',
          'return',
        ],
      },
    ],
    'no-empty-source': null,
    'named-grid-areas-no-invalid': null,
    'no-descending-specificity': null,
    'font-family-no-missing-generic-family-keyword': null,
    'media-query-no-invalid': null,
    'rule-empty-line-before': [
      'always',
      {
        ignore: ['after-comment', 'first-nested'],
      },
    ],
    'unit-no-unknown': [true, { ignoreUnits: ['rpx'] }],
    'no-duplicate-selectors': null,
    'no-invalid-position-declaration': null,
  },
};

4).settings.json增加

"source.fixAll.stylelint": "explicit"

"stylelint.enable": true,
 "stylelint.validate": [
   "css",
   "less",
   "scss",
   "pcss",
   "postcss",
   "vue"
 ],

在这里插入图片描述
在这里插入图片描述
完整的.settings.json

{
  "explorer.fileNesting.enabled": true,
  "explorer.fileNesting.patterns": {
    "tsconfig.json": "tsconfig.*.json, env.d.ts",
    "vite.config.*": "jsconfig*, vitest.config.*, cypress.config.*, playwright.config.*",
    "package.json": "package-lock.json, pnpm*, .yarnrc*, yarn*, .eslint*, eslint*, .oxlint*, oxlint*, .prettier*, prettier*, .editorconfig"
  },
  // Disable the default formatter, use eslint instead
  "prettier.enable": false,
  "editor.formatOnSave": false,

  // Auto fix
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit",
    "source.organizeImports": "never",
    "source.fixAll.stylelint": "explicit"
  },

  // Silent the stylistic rules in you IDE, but still auto fix them
  "eslint.rules.customizations": [
    { "rule": "style/*", "severity": "off", "fixable": true },
    { "rule": "format/*", "severity": "off", "fixable": true },
    { "rule": "*-indent", "severity": "off", "fixable": true },
    { "rule": "*-spacing", "severity": "off", "fixable": true },
    { "rule": "*-spaces", "severity": "off", "fixable": true },
    { "rule": "*-order", "severity": "off", "fixable": true },
    { "rule": "*-dangle", "severity": "off", "fixable": true },
    { "rule": "*-newline", "severity": "off", "fixable": true },
    { "rule": "*quotes", "severity": "off", "fixable": true },
    { "rule": "*semi", "severity": "off", "fixable": true }
  ],

  // Enable eslint for all supported languages
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "vue",
    "html",
    "markdown",
    "json",
    "json5",
    "jsonc",
    "yaml",
    "toml",
    "xml",
    "gql",
    "graphql",
    "astro",
    "svelte",
    "css",
    "less",
    "scss",
    "pcss",
    "postcss"
  ],
  "stylelint.enable": true,
  "stylelint.validate": [
    "css",
    "less",
    "scss",
    "pcss",
    "postcss",
    "vue"
  ],
}


网站公告

今日签到

点亮在社区的每一天
去签到