配置代码质量工具(Prettier、ESLint、Stylelint)配置ctrl+s保存后自动修复

代码规范配置 与 自动调整格式工具

一. 风格工具

我们主要使用一下几个依赖与vscode插件

  • ESLint: 是一款用于查找并报告代码中问题的工具
  • Stylelint: 是一个强大的现代 CSS 检测器
  • Prettier: 是一款强大的代码格式化工具,支持多种语言
  • lint-staged: 是一个在 git 暂存文件上运行 linters 的工具
  • husky: 是 Git Hook 工具,可以设置在 git 各个阶段触发设定的命令

1. editorconfig

https://editorconfig.org/
EditorConfig 的优先级高于编辑器自身的配置,因此可用于维护不同开发人员、不同编辑器的编码风格。编码风格:缩进风格、换行符类型、字符编码等。

在项目根目录下增加 .editorconfig 文件进行配置即可,以下为参考配置:

# 表示这是项目根目录下的顶级 .editorconfig 文件,编辑器在查找配置时会停止向上查找
root = true

[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行

[*.md] # 表示仅 md 文件适用以下规则
indent_style = tab # 使用制表符缩进
max_line_length = off
trim_trailing_whitespace = false

VSCode需要安装一个插件:EditorConfig for VS Code
在这里插入图片描述
常见配置项:

  • root:是否是项目根目录下的顶级 .editorconfig 文件。
  • indent_style:缩进风格,可以是 tab(制表符)或 space(空格)。
  • indent_size:缩进大小,对于 tab 缩进风格无效。
  • tab_width:制表符宽度,用于 tab 缩进风格。
  • end_of_line:换行符类型,可以是 lf(Unix 风格)、crlf(Windows 风格)或 cr(旧版 Mac 风格)。
  • charset:字符编码,通常设置为 utf-8。
  • trim_trailing_whitespace:是否去除行末多余的空格。
  • insert_final_newline:文件末尾是否插入空行。 以上是一些常见的配置项,具体可以根据项目需要进行配置。详细的配置项列表和说明可以参考EditorConfig 官方文档。
    参考资料:https://editorconfig.org/

2. prettier

https://www.prettier.cn/docs/configuration.html

Prettier 是一款强大的代码格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等语言,基本上前端能用到的文件格式它都可以搞定,是当下最流行的代码格式化工具。

2.1使用

安装prettier:pnpm add prettier -D
vscode 也需要安装插件
在这里插入图片描述

配置.prettierrc文件:

  printWidth: 100, // 每行代码长度(默认80)
  tabWidth: 2, // 每个tab相当于多少个空格(默认2)ab进行缩进(默认false)
  useTabs: false, // 是否使用tab
  semi: false, // 声明结尾使用分号(默认true)
  vueIndentScriptAndStyle: false,
  singleQuote: true, // 使用单引号(默认false)
  quoteProps: 'as-needed',
  bracketSpacing: true, // 对象字面量的大括号间使用空格(默认true)
  trailingComma: 'none', // 多行使用拖尾逗号(默认none)
  jsxSingleQuote: false,
  // 箭头函数参数括号 默认avoid 可选 avoid| always
  // avoid 能省略括号的时候就省略 例如x => x
  // always 总是有括号
  arrowParens: 'always',
  insertPragma: false,
  requirePragma: false,
  proseWrap: 'never',
  htmlWhitespaceSensitivity: 'strict',
  endOfLine: 'auto',
  rangeStart: 0

同时支持以下格式

  • "prettier"您的文件中的密钥package.json。
  • 以 JSON 或 YAML 编写的文件.prettierrc。
  • 、、或文件.prettierrc.json。.prettierrc.yml.prettierrc.yaml.prettierrc.json5
  • 使用或导出对象的.prettierrc.js、 或文件(取决于中的值)。prettier.config.jsexport defaultmodule.exportstypepackage.json
  • .prettierrc.mjs或prettier.config.mjs使用 导出对象的文件export default。
  • .prettierrc.cjs或prettier.config.cjs使用 导出对象的文件module.exports。
  • 一个.prettierrc.toml文件。
    参考资料https://www.prettier.cn/docs/configuration.html
2.2. 测试prettier是否生效

测试一:在代码中保存代码;
测试二:配置一次性修改的命令;
在package.json中配置一个scripts:

"prettier": "prettier --write ."
2.3 配置保存自动格式化

建议为每个项目添加vscode独有的设置,也就是在项目的根目录中创建一个.vscode目录,里面放置一个setting.json文件,这样vscode会优先读取该设置。
这样可以保证别人下载你的项目进行开发时,也不会因为全局setting.json的配置不同而导致Prettier或者ESLint、StyleLint失效,接下来在该文件内输入以下代码:

注意: setting.json与.prettier中有相同的配置时都会执行,但是.prettier的优先级高于setting.json

{
  // 指定 TypeScript 的 SDK 路径,告诉 VS Code 使用项目本地安装的 TypeScript,而不是全局安装的版本。
  // 这样可以确保 TypeScript 的版本与项目的依赖一致,避免版本不匹配导致的问题。
  "typescript.tsdk": "node_modules/typescript/lib",
  // 包管理工具
  "npm.packageManager": "pnpm",
  // 设置 Tab 的宽度为 2 个空格
  "editor.tabSize": 2,
  // 配置 Prettier 的最大行宽为 100,超过此宽度会自动换行。
  "prettier.printWidth": 100, // 超过最大值换行
  // 指定默认的代码格式化工具为 Prettier
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  // 设置文件的换行符为 \n(Unix 风格)
  "files.eol": "\n",
  // 搜索排除规则 vscode搜索时的排除规则
  "search.exclude": {
    "**/node_modules": true,
    "**/*.log": true,
    "**/*.log*": true,
    "**/bower_components": true,
    "**/dist": true,
    "**/elehukouben": true,
    "**/.git": true,
    "**/.gitignore": true,
    "**/.svn": true,
    "**/.DS_Store": true,
    "**/.idea": true,
    "**/.vscode": false,
    "**/yarn.lock": true,
    "**/tmp": true,
    "out": true,
    "dist": true,
    "node_modules": true,
    "CHANGELOG.md": true,
    "examples": true,
    "res": true,
    "screenshots": true,
    "yarn-error.log": true,
    "**/.yarn": true
  },
  // 配置vscode文件资源管理器中需要隐藏的文件或文件夹
  "files.exclude": {
    "**/.cache": true,
    "**/.editorconfig": true,
    "**/.eslintcache": true,
    "**/bower_components": true,
    "**/.idea": true,
    "**/tmp": true,
    "**/.git": true,
    "**/.svn": true,
    "**/.hg": true,
    "**/CVS": true,
    "**/.DS_Store": true
  },
  // 文件监视排除规则 例如mode_modules文件夹下的文件有变动也不需要监视
  "files.watcherExclude": {
    "**/.git/objects/**": true,
    "**/.git/subtree-cache/**": true,
    "**/.vscode/**": true,
    "**/node_modules/**": true,
    "**/tmp/**": true,
    "**/bower_components/**": true,
    "**/dist/**": true,
    "**/yarn.lock": true
  },
  // 启用 Stylelint 插件,用于检查 CSS、Less、SCSS 等文件的样式问题
  "stylelint.enable": true,
  "css.validate": false,
  "less.validate": false,
  "scss.validate": false,
  // 配置了需要校验的文件类型,包括 vue 文件
  "stylelint.validate": ["css", "less", "postcss", "scss", "vue", "sass"],
  // 路径别名映射
  "path-intellisense.mappings": {
    "@/": "${workspaceRoot}/src"
  },
  /*
    语言格式化工具
    esbenp.prettier-vscode Prettier 
    rvest.vs-code-prettier-eslint Prettier-ESLint
  */
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
  },
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[css]": {
    "editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
  },
  "[less]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[vue]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  // 保存自动格式化
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit",
    "source.fixAll.stylelint": "explicit"
  },
  "i18n-ally.localesPaths": ["src/locales"],
  "i18n-ally.keystyle": "nested",
  "i18n-ally.sortKeys": true,
  "i18n-ally.namespace": false,
  "i18n-ally.enabledParsers": ["ts"],
  "i18n-ally.sourceLanguage": "en",
  "i18n-ally.displayLanguage": "zh-CN",
  "i18n-ally.enabledFrameworks": ["vue", "react"],
  // cSpell.words 是 VS Code 的拼写检查插件 Code Spell Checker 的配置项
  "cSpell.words": [
    "brotli",
    "browserslist",
    "codemirror",
    "commitlint",
    "cropperjs",
    "echart",
    "echarts",
    "esnext",
    "pinia",
    "pnpm",
    "qrcode",
    "sider",
    "sortablejs",
    "stylelint",
    "svgs",
    "unocss",
    "unplugin",
    "unref",
    "videojs",
    "vueuse",
    "wangeditor"
  ],
  // 控制相关文件嵌套展示
  "explorer.fileNesting.enabled": true,
  "explorer.fileNesting.expand": false,
  "explorer.fileNesting.patterns": {
    "*.ts": "$(capture).test.ts, $(capture).test.tsx",
    "*.tsx": "$(capture).test.ts, $(capture).test.tsx",
    "*.env": "$(capture).env.*",
    "package.json": "pnpm-lock.yaml,yarn.lock,LICENSE,README*,CHANGELOG*,CNAME,.gitattributes,.eslintrc-auto-import.json,.gitignore,prettier.config.js,stylelint.config.js,commitlint.config.js,.stylelintignore,.prettierignore,.gitpod.yml,.eslintrc.js,.eslintignore"
  },
  "terminal.integrated.scrollback": 10000,
  "nuxt.isNuxtApp": false
}


editor.formatOnSave的作用是在我们保存时,会自动执行一次代码格式化,而我们该使用什么格式化器?接下来的代码便是设置默认的格式化器,看名字大家也能看得出来了吧!
在遇到 .js 、 .jsx 、.ts 、.tsx 、.json 、.html 、.md 、 .css 、 .less 、 .scss 为后缀的文件时,都会去使用 Prettier 去格式化代码,而格式化的规则就是我们配置的 .prettierrc 决定的!

2.4.prettierignore

忽略格式化的文件

/dist/*
.local
.output.js
/node_modules/**
*/.svg
**/
.sh
/public/

二. 质量工具

1.ESLint

https://eslint.org/docs/latest/use/configure/configuration-files
ESLint 是一个用于 JavaScript 代码的静态代码分析工具,它可以帮助开发人员发现和修复代码中的问题,确保代码的质量和一致性。ESLint 可以检查代码中的语法错误、代码风格问题以及可能的逻辑错误。
相较于ESLint9的更新
不再支持Node<v18.18.0版本了,以前的老版本Node已经跑不起最新的ESLint9了
配置文件格式的改动:
全面采用扁平配置系统,移除旧版层级配置
移除对.eslintrc文件的支持
现配置文件更改为eslint.config.js|eslint.config.cjs|eslint.config.mjs
使用者只需要关心上面2个,至于API方面可以去官网查找。

关于配置文件改动肯定是最大的一部分,因为很多插件是还没有适配过来的,官网有一篇配置迁移指南可以参考 https://eslint.org/docs/latest/use/configure/configuration-files

1.1安装ESLint9

vscode 安装插件
在这里插入图片描述

1.2安装依赖:

安装依赖
pnpm add eslint -D

1.3执行

pnpm create @eslint/config@latest
根据提示进行选择
在这里插入图片描述
此时根目录下会生成eslint.config.js文件,这是eslint最新的配置文件。打开文件,内容如下:

import js from "@eslint/js";
import globals from "globals";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
import css from "@eslint/css";
import { defineConfig } from "eslint/config";


export default defineConfig([
  { files: ["**/*.{js,mjs,cjs,ts,vue}"], plugins: { js }, extends: ["js/recommended"] },
  { files: ["**/*.{js,mjs,cjs,ts,vue}"], languageOptions: { globals: {...globals.browser, ...globals.node} } },
  tseslint.configs.recommended,
  pluginVue.configs["flat/essential"],
  { files: ["**/*.vue"], languageOptions: { parserOptions: { parser: tseslint.parser } } },
  { files: ["**/*.css"], plugins: { css }, language: "css/css", extends: ["css/recommended"] },
]);

关于代码保存自动格式化 setting.json中已经配置过了 并且标明了注释 可上划查看

2.3 ESLint与Prettier冲突
有时候ESLint定义的规则会与prettier定义的规则发生冲突,我们可以使用eslint-plugin-prettier。
这个插件不仅提供文件解析、代码fix,也顺带提供了一些规则配置。在ESlint与prettier发生冲突时,这个插件会将冲突规则的ESlint给off掉。也就是说,二选一,优先选择prettier。

pnpm add eslint-plugin-prettier -D
import eslintPluginPrettier from "eslint-plugin-prettier";

/** @type {import('eslint').Linter.Config[]} */
export default defineConfig([
  ...其他代码
  eslintPluginPrettier,
]);

2.styleLint

https://stylelint.node.org.cn/user-guide/configure/
StyleLint 是一个支持多种样式语言、可高度定制、支持插件扩展和自动修复的现代 CSS 样式检查工具,适合集成到编辑器和构建工具中以保持代码风格一致性和提高代码质量。
要开始使用 StyleLint,首先需要安装 StyleLint 包,然后在项目中配置一个 .stylelintrc 文件来指定检查规则。可以通过命令行工具或与构建过程集成来运行 StyleLint。当 StyleLint 检测到问题时,它会生成报告,其中包含有关问题的详细信息和建议的修复方法。

2.1安装

同时需要安装vscode 插件
在这里插入图片描述

pnpm add stylelint stylelint-config-standard stylelint-config-recommended stylelint-config-html  stylelint-order -D
2.2配置.stylelintrc.js文件

可以从此处查询详细内容https://stylelint.node.org.cn/user-guide/configure/

可以使用.stylelintrc.js 我这里使用的是stylelint.config.cjs文件
Stylelint 期望一个配置对象,并在以下文件中查找:
stylelint.config.js 或 .stylelintrc.js 文件
使用哪个模块系统取决于您的 Node.js 默认模块系统配置(例如,package.json 中的 “type”: “module”)。
stylelint.config.mjs 或 .stylelintrc.mjs 文件,使用 export default(ES 模块)
stylelint.config.cjs 或 .stylelintrc.cjs 文件,使用 module.exports(CommonJS)
.stylelintrc.json、.stylelintrc.yml 或 .stylelintrc.yaml 文件
.stylelintrc 文件,以 JSON 或 YAML 格式
我们建议添加扩展名(例如,.json),以帮助您的编辑器提供语法检查和高亮显示。
package.json 中的 stylelint 属性

module.exports = {
  root: true,
  plugins: ['stylelint-order'],
  customSyntax: 'postcss-html',
  extends: ['stylelint-config-standard'],
  rules: {
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['global', 'deep']
      }
    ],
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: ['function', 'if', 'each', 'include', 'mixin', 'extend']
      }
    ],
    'media-query-no-invalid': null,
    'function-no-unknown': null,
    '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': null,
    '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'
      }
    ],
    // Specify the alphabetical order of the attributes in the declaration block
    'order/properties-order': [
      'position',
      'top',
      'right',
      'bottom',
      'left',
      'z-index',
      'display',
      'float',
      'width',
      'height',
      'max-width',
      'max-height',
      'min-width',
      'min-height',
      'padding',
      'padding-top',
      'padding-right',
      'padding-bottom',
      'padding-left',
      'margin',
      'margin-top',
      'margin-right',
      'margin-bottom',
      'margin-left',
      'margin-collapse',
      'margin-top-collapse',
      'margin-right-collapse',
      'margin-bottom-collapse',
      'margin-left-collapse',
      'overflow',
      'overflow-x',
      'overflow-y',
      'clip',
      'clear',
      'font',
      'font-family',
      'font-size',
      'font-smoothing',
      'osx-font-smoothing',
      'font-style',
      'font-weight',
      'hyphens',
      'src',
      'line-height',
      'letter-spacing',
      'word-spacing',
      'color',
      'text-align',
      'text-decoration',
      'text-indent',
      'text-overflow',
      'text-rendering',
      'text-size-adjust',
      'text-shadow',
      'text-transform',
      'word-break',
      'word-wrap',
      'white-space',
      'vertical-align',
      'list-style',
      'list-style-type',
      'list-style-position',
      'list-style-image',
      'pointer-events',
      'cursor',
      'background',
      'background-attachment',
      'background-color',
      'background-image',
      'background-position',
      'background-repeat',
      'background-size',
      'border',
      'border-collapse',
      'border-top',
      'border-right',
      'border-bottom',
      'border-left',
      'border-color',
      'border-image',
      'border-top-color',
      'border-right-color',
      'border-bottom-color',
      'border-left-color',
      'border-spacing',
      'border-style',
      'border-top-style',
      'border-right-style',
      'border-bottom-style',
      'border-left-style',
      'border-width',
      'border-top-width',
      'border-right-width',
      'border-bottom-width',
      'border-left-width',
      'border-radius',
      'border-top-right-radius',
      'border-bottom-right-radius',
      'border-bottom-left-radius',
      'border-top-left-radius',
      'border-radius-topright',
      'border-radius-bottomright',
      'border-radius-bottomleft',
      'border-radius-topleft',
      'content',
      'quotes',
      'outline',
      'outline-offset',
      'opacity',
      'filter',
      'visibility',
      'size',
      'zoom',
      'transform',
      'box-align',
      'box-flex',
      'box-orient',
      'box-pack',
      'box-shadow',
      'box-sizing',
      'table-layout',
      'animation',
      'animation-delay',
      'animation-duration',
      'animation-iteration-count',
      'animation-name',
      'animation-play-state',
      'animation-timing-function',
      'animation-fill-mode',
      'transition',
      'transition-delay',
      'transition-duration',
      'transition-property',
      'transition-timing-function',
      'background-clip',
      'backface-visibility',
      'resize',
      'appearance',
      'user-select',
      'interpolation-mode',
      'direction',
      'marks',
      'page',
      'set-link-source',
      'unicode-bidi',
      'speak'
    ]
  },
  ignoreFiles: ['**/*.js', '**/*.jsx', '**/*.tsx', '**/*.ts'],
  overrides: [
    {
      files: ['*.vue', '**/*.vue', '*.html', '**/*.html'],
      extends: ['stylelint-config-recommended', 'stylelint-config-html'],
      rules: {
        'keyframes-name-pattern': null,
        'selector-class-pattern': null,
        'no-duplicate-selectors': null,
        'selector-pseudo-class-no-unknown': [
          true,
          {
            ignorePseudoClasses: ['deep', 'global']
          }
        ],
        'selector-pseudo-element-no-unknown': [
          true,
          {
            ignorePseudoElements: ['v-deep', 'v-global', 'v-slotted']
          }
        ]
      }
    }
  ]
}

2.3配置保存自动修复

安装vscode插件后 在.vscode/settings.json文件中开启自动修复 全量配置代码 可以在上文中查找

  // 启用 Stylelint 插件,用于检查 CSS、Less、SCSS 等文件的样式问题
  "stylelint.enable": true,
  "css.validate": false,
  "less.validate": false,
  "scss.validate": false,
  // 配置了需要校验的文件类型,包括 vue 文件
  "stylelint.validate": ["css", "less", "postcss", "scss", "vue", "sass"],

同类文章标记 Vue3+Ts+Pnpm+eslint9.0+Prettier+Stylelint+vant(移动/h5)项目搭建记录
本文内容部分收集于 如果需要commit的时候校验规则 可以从此文章找到
基础环境搭建-初始化项目与代码质量工具配置(Prettier、ESLint、Stylelint、Lint-staged、Husky)
开源项目 宇道源码
配置demo可以从看该仓库的commithttps://github.com/kingHjp/my-vite-create-vue3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值