Skip to content

代码风格工具集成

作者:Atom
字数统计:5.2k 字
阅读时长:22 分钟

前端工程化的过程中, 必须借助各种各样的工具来完成。 本篇来探索代码风格审查工具的集成和应用, 所涉及的IDE(VSCode)工具插件如下

此外还有一部分Npm插件配合使用

首先需要安装以上一些IDE插件, 以便于在开发过程中, 及时的发现代码风格问题, 并且修复

基本配置

征对上述的工具, 每个工具都有相应的使用场景:

  • 与编辑器相关的所有配置(结尾行、缩进风格、缩进大小等等)应该由 EditorConfig 来处理
  • 代码格式相关的一切事物应该由 Prettier 处理
  • 剩下的代码质量则由 ESLint 负责
  • StyleLint用于处理样式文件的代码风格和质量
  • Husky用于在代码提交的时候进行卡点检查

接下来, 我们先对所有的插件进行最基本的依赖安装和初始化基本配置文件

ESLint

官方的定位是用于检测并修复代码中的问题, 即风格统一代码优化, 属于代码质量检测工具

首先安装ESLint, 并为其创建配置文件.eslintrc.js

sh
# 安装eslint依赖
pnpm i eslint -D
# 初始化eslint配置
npx eslint --init
js
// .eslintrc.js
module.exports = {
  // 全局环境变量
  globals: {
    $: false, // true表示变量可重写 false表示变量不可重写  off表示禁用该全局变量
    jQuery: false
  },
  // 运行环境变量
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  extends: 'eslint:recommended'
}

Prettier

ESLint 的主要优势在于代码的风格检查并给出提示,而在代码格式化这一块 Prettier 做的更加专业,因此我们经常将 ESLint 结合 Prettier 一起使用

同样安装对应的依赖和创建基本配置文件prettier.config.js

sh
pnpm i prettier -D
js
// prettier.config.js
/** @type {import("prettier").Config} */
module.exports = {
  printWidth: 80, //一行的字符数,如果超过会进行换行,默认为80
  singleQuote: true, // 字符串是否使用单引号,默认为 false,使用双引号
  semi: false, // 行尾是否使用分号,默认为true
  trailingComma: 'none', // 是否使用尾逗号
  bracketSpacing: true // 对象大括号直接是否有空格,默认为 true,效果:{ a: 1 }
}

EditorConfig

简短来说, 与编辑器相关的所有配置(结尾行、缩进风格、缩进大小等等)应该由 EditorConfig 来处理, 以便于在不同的编辑器和IDE中保持一致的风格

官方定义

EditorConfig 有助于跨不同编辑器和 IDE 处理同一项目的多个开发人员保持一致的编码风格。EditorConfig 项目由用于定义编码样式的文件格式和文本编辑器插件集合组成,这些插件使编辑器能够读取文件格式并遵守定义的样式。EditorConfig 文件易于读​​取,并且可以很好地与版本控制系统配合使用

同样创建配置文件.editorconfig, 它支持的选项总共如下:

  • indent_style

    设置为tabspace分别使用硬制表符或软制表符

  • indent_size

    一个整数,定义用于每个缩进级别的列数和软选项卡的宽度(如果支持), 当index_style设置为space时, 该值为缩进的空格数

  • tab_width

    定义用于表示制表符的列数的整数。当index_style设置为tab时, 就使用tabtab_width的值(如果指定)

  • end_of_line

    设置为lfcrcrlf以控制换行符的表示方式

  • charset

    设置为latin1utf-8utf-8-bomutf-16beutf-16le来控制字符集

  • trim_trailing_whitespace

    设置为true以删除换行符之前的所有空白字符,设置为false以确保不会删除换行符

  • insert_final_newline

    设置为true以确保文件在保存时以换行符结尾,设置为false以确保文件不以换行符结尾

  • root

    应在文件顶部任何部分之外指定的特殊属性。设置为true以停止.editorconfig对当前文件的文件搜索

yaml
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
charset = utf-8
# 设置space使用index_size, 设置为tab使用tab_width
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

StyleLint

StyleLint 是一个强大的工具,用于检查 CSS 代码中的错误和风格问题。它可以帮助我们避免错误,以及在团队中保持一致的风格

它主要专注于样式代码的规范检查,内置了 170 多个 CSS 书写规则,支持 CSS 预处理器(如 SassLess),提供插件化机制以供开发者扩展规则,已经被 GoogleGithub 等大型团队投入使用

同样安装相关依赖和创建对应的配置文件stylelint.config.js

sh
pnpm i stylelint stylelint-config-recess-order stylelint-config-standard stylelint-config-standard-scss -D
js
// stylelint.config.js
module.exports = {
  // 继承一系列规则集合
  extends: [
    // standard 规则集合
    'stylelint-config-standard',
    // standard 规则集合的 scss 版本
    'stylelint-config-standard-scss',
    // 样式属性顺序规则
    'stylelint-config-recess-order',
  ]
}

Husky

在上文中安装的 ESLintPrettierStyleLintVSCode 插件,在开发阶段提前规避掉代码格式的问题,但实际上这也只是将问题提前暴露,并不能保证规范问题能完全被解决,还是可能导致线上的代码出现不符合规范的情况。那么如何来避免这类问题呢?

我们可以在代码提交的时候进行卡点检查,也就是拦截 git commit 命令,进行代码格式检查,只有确保通过格式检查才允许正常提交代码。这也就是本段提到的Husky工具

依然如上文一样, 安装依赖和创建初始化配置

sh
# 安装依赖
pnpm i husky -D
# 使用命令初始化配置文件
npx husky install
# 添加pre-commit钩子, .husky目录下将创建pre-commit脚本
npx husky add .husky/pre-commit "npm run lint"

为了保证克隆下来的项目, 都能创建到对应的钩子, 需要在package.json下面的script条目中设置对应的初始化安装命令

json
// package.json
{
  "scripts": {
    // 会在安装 npm 依赖后自动执行
    "prepare": "husky install"
  }
}

集成工具配置

上面的多个工具单独使用都无法发挥出最大的作用,因此需要将它们集成起来,以便于在开发过程中,及时的发现代码风格问题,并且修复

ESLint + Prettier

两者使用的过程中, 应该注意以下场景中遇到的问题

场景一、让ESLint中也提示Prettier的检查错误

ESLintPrettier 的集成主要是通过 eslint-plugin-prettier 插件来实现的,它会将 Prettier 的规则作为 ESLint 的规则来运行,这样就可以使用 ESLint 的规则来检测代码格式了

首先安装ESLintPrettier集成的相关依赖, 然后配置ESLint的配置文件.eslintrc.js

sh
pnpm i eslint-plugin-prettier -D
js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  extends: ['eslint:recommended'],
  // 此处的prettier用于让ESLint适配prettier的规则
  plugins: ['prettier'], 
  rules: {                
    'prettier/prettier': 'error'
  } 
}

场景二、配置相互冲突

该种场景下, 应该停用可能与 Prettier 冲突的所有 ESLint 规则(仅指代码格式规则)。最佳方案是使用社区插件 eslint-config-prettier 来解决

首先安装Prettier的相关依赖, 然后修改ESLint的配置文件.eslintrc.js

注意

ESLint配置文件的 extends 数组的顺序非常重要。基本上,每次一个新配置添加到这个数组中,它都会覆盖前面的配置。因此,prettier 位于数组尾部至关重要,以确保它可以覆盖其他配置。此时尽管放心,ESLint(质量检测) 不会再尝试做 Prettier(格式代码) 的工作了

sh
pnpm i eslint-config-prettier -D
js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  extends: [
    'eslint:recommended',
    // 此处prettier用于解决二者的冲突规则, 确保prettier是最后一项, 可以覆盖前面的配置的冲突项
    // 1. 接入 prettier 的规则
    'prettier', 
    'plugin:prettier/recommended'
  ],
  plugins: ['prettier'],
  rules: {
    'prettier/prettier': 'error'
  }
}

集成Typescript

如今我们需要在原有的配置上, 支持集成Typescript, 那应该怎么做呢?

初始化Typescript

首先安装Typescript的相关依赖, 然后初始化Typescript配置文件tsconfig.json

sh
pnpm install typescript -D
json
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
    "lib": [
      "DOM",
      "ES2015"
    ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "ESNext" /* Specify what module code is generated. */,
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    "sourceMap": true /* Create source map files for emitted JavaScript files. */,
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

    /* Type Checking */
    "strict": true /* Enable all strict type-checking options. */,
    // "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */,
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  },
  "include": ["src/**/*", "rollup.config.ts"]
}

修改ESLint配置文件

为了让 ESLintTypeScript 或其他带有特定语法的框架兼容,我们需要添加一个解析器,以便 ESLint 可以读取新加插件中新代码以及与 TypeScript(或任何其他需要解析器的框架)相关的一套新规则

然后,我们通过在 parser 选项中添加 TypeScript 解析器并将插件添加到 extends 数组中来修改 .eslintrc.js 文件以包含 TypeScript

首先安装相关依赖, 然后再修改ESLint配置文件

sh
pnpm install typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin -D
js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  parser: '@typescript-eslint/parser', 
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended', 
    // 此处prettier用于解决二者的冲突规则, 确保prettier是最后一项, 可以覆盖前面的配置的冲突项
    // 1. 接入 prettier 的规则
    'prettier',
    'plugin:prettier/recommended'
  ],
  plugins: ['@typescript-eslint', 'prettier'], 
  rules: {
    'prettier/prettier': 'error',
    '@typescript-eslint/no-unused-vars': 'warn'
  }
}

Prettier + EditorConfig

最开始我们定义的配置文件.editorconfig已经能够自动格式化代码的缩进, 末尾插入行, 删除多余空格, 控制代码编码等等。 但是它并不能自动格式化代码的风格, 因此我们需要借助Prettier来实现

值得注意的是PrettierEditorConfig有一部分配置是重复的, 且Prettier首先读取.editorconfig的配置, 然后再根据自身的配置来格式化代码, 因此需要删除它们的冲突项

它们的冲突项主要如下:

  • end_of_line: 等同于PrettierendOfLine配置
  • indent_style: 等同于PrettieruseTabs配置
  • indent_size: 等同于PrettiertabWidth配置
  • tab_width: 等同于PrettiertabWidth配置
  • max_line_length: 等同于PrettierprintWidth配置

解决方案

征对冲突选项, 不应该在Prettier中设置以上冲突的选项

StyleLint + Prettier

同时使用StyleLintPrettier, 也需要安装对应的插件, 才能更好的配合使用

场景一、 让StyleLint中也提示Prettier的检查错误

首先安装对应的依赖stylelint-prettier, 使其支持Prettier中检查到的样式错误, 然后再修改配置文件

sh
pnpm i stylelint-prettier -D
js
// stylelint.config.js
module.exports = {
  // 注册 stylelint 的 prettier 插件
  plugins: ['stylelint-prettier'], 
  // 继承一系列规则集合
  extends: [
    // standard 规则集合
    'stylelint-config-standard',
    // standard 规则集合的 scss 版本
    'stylelint-config-standard-scss',
    // 样式属性顺序规则
    'stylelint-config-recess-order',
  ],
  // 配置 rules
  rules: { 
    // 开启 Prettier 自动格式化功能
    'prettier/prettier': true
  } 
}

场景二、接入Prettier规则, 并解决冲突

首先安装依赖stylelint-config-prettier, 然后修改对应的配置文件

sh
pnpm i stylelint-config-prettier stylelint-config-prettier -D
js
// stylelint.config.js
module.exports = {
  // 注册 stylelint 的 prettier 插件
  plugins: ['stylelint-prettier'],
  // 继承一系列规则集合
  extends: [
    // standard 规则集合
    'stylelint-config-standard',
    // standard 规则集合的 scss 版本
    'stylelint-config-standard-scss',
    // 样式属性顺序规则
    'stylelint-config-recess-order',
     // 接入 Prettier 规则
    'stylelint-config-prettier', 
    'stylelint-prettier/recommended'
  ],
  // 配置 rules
  rules: {
    // 开启 Prettier 自动格式化功能
    'prettier/prettier': true
  }
}

配置自动化命令

在上述的配置完成后, 我们需要配置一些自动化的命令, 以便于在开发过程中, 及时的发现代码风格问题, 并且修复

这一步, 在package.json中定义与上述工具相关的脚本即可

json
{
  "script": {
    "prepare": "husky install",
    "eslint": "eslint src --ext .js,.jsx,.ts,.tsx,.vue --cache", 
    "eslint:fix": "npm run eslint -- --fix", 
    "prettier": "prettier --check .", 
    "prettier:fix": "prettier --write .", 
    "stylelint": "stylelint \"src/**/*.{css,scss,less}\"", 
    "stylelint:fix": "stylelint \"src/**/*.{css,scss,less}\" --fix", 
    "lint": "pnpm run eslint && pnpm run stylelint && pnpm run prettier", 
    "lint:fix": "pnpm run eslint:fix && pnpm run stylelint:fix && pnpm run prettier:fix"
  }
}

Husky + LintStaged

Husky能通过Git钩子拦截一些代码管理的行为(提交、推送等等), 比如在用户提交代码的阶段, 可以使用pre-commit钩子进行拦截。然后通过Husky配置对应的操作行为脚本, 就实现了代码风格提交预检查

但是Husky中配置的脚本, 会对所有的文件进行检查, 这样就会导致一些不必要的性能损耗, 因此我们需要借助LintStaged来解决这个问题

LintStaged仅仅对暂存区的文件进行处理, 从而提高了检查的性能

首先应该安装lint-staged插件, 然后创建对应的配置文件lint-staged.config.js

sh
pnpm i lint-staged -D
js
// lint-staged.config.js
module.exports = {
  "*.{js,jsx,ts,tsx,vue}": [
    "pnpm run eslint",
    "pnpm run prettier",
    "git add ."
  ],
  "*.{scss,less,css,stylus,styl}": [
    "pnpm run stylelint",
    "git add ."
  ]
}

配置文件配好了之后, 就需要让Husky来调用它, 以便于在提交代码的时候, 进行代码风格的检查。因此调用下面的命令, 修改Husky中配置的命令

sh
npx husky set .husky/pre-commit "npx --no -- lint-staged"

Husky + CommitLint

除了代码规范检查之后,Git 提交信息的规范也是不容忽视的一个环节,规范的 commit 信息能够方便团队协作和问题定位。首先我们来安装一下需要的工具库,执行如下的命令

sh
pnpm i commitlint @commitlint/cli @commitlint/config-conventional -D

接下来创建对应的CommitLint的配置文件.commitlintrc.js

js
// .commitlintrc.js
module.exports = {
  extends: ["@commitlint/config-conventional"]
};

最后一步, 将Commitlint的功能集成到 Husky 的钩子当中,在终端执行如下命令即可:

sh
npx husky add .husky/commit-msg "npx --no-install commitlint -e $HUSKY_GIT_PARAMS"

命令执行完之后,.husky目录下多出了commit-msg脚本文件,表示Commitlint命令已经成功接入到 husky 的钩子当中

框架应用配置

在React中集成

React应用中集成ESLint比较简单, 只需要安装eslint-plugin-react插件, 然后修改ESLint配置即可

sh
pnpm i eslint-plugin-react@latest -D
js
// .eslintrc.js
//
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaFeatures: { 
      jsx: true
    }, 
    ecmaVersion: "latest",
    sourceType: "module"
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended', 
    'plugin:@typescript-eslint/recommended',
    // 1. 接入 prettier 的规则
    'prettier',
    'plugin:prettier/recommended'
  ],
  // 2. 加入 prettier 的 eslint 插件
  plugins: ['react', '@typescript-eslint', 'prettier'], 
  rules: {
    'no-unused-vars': 'warn',
    'prettier/prettier': 'error',
    '@typescript-eslint/no-unused-vars': 'warn',
    'react/react-in-jsx-scope': 'off'
  }
}

在Vue3中集成

为了在Vue3应用下集成以上多个工具, 先装好对应的依赖

修改ESLint

首先应该安装Vue3的相关ESLint插件eslint-plugin-vue@latest

sh
pnpm i eslint-plugin-vue@latest -D

然后修改.eslintrc.js, 此处我们需要将.eslintrc.js文件下的"parser": "@typescript-eslint/parser" 移动到parserOptions中, 然后新增parser: vue-eslint-parser, 因为eslint-plugin-vue规定如果用了其它解析器则需要将其移动到parseOptions下才不会发生冲突

js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  parser: 'vue-eslint-parser', 
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    parser: '@typescript-eslint/parser'
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-essential', 
    // 1. 接入 prettier 的规则
    'prettier',
    'plugin:prettier/recommended'
  ],
  // 2. 加入 prettier 的 eslint 插件
  plugins: ['vue', '@typescript-eslint', 'prettier'], 
  rules: {
    'no-unused-vars': 'warn',
    'prettier/prettier': 'error',
    '@typescript-eslint/no-unused-vars': 'warn'
  }
}

修改StyleLint

同上, 先安装依赖, 再修改配置文件

sh
pnpm i stylelint-config-recommended-vue -D
js
// stylelint.config.js
module.exports = {
  // 注册 stylelint 的 prettier 插件
  plugins: ['stylelint-prettier'],
  // 继承一系列规则集合
  extends: [
    // standard 规则集合
    'stylelint-config-standard',
    // standard 规则集合的 scss 版本
    'stylelint-config-standard-scss',
    'stylelint-config-recess-order'
    // vue 规则集合
    'stylelint-config-recommended-vue'
  ],
  // 配置 rules
  rules: {
    // 开启 Prettier 自动格式化功能
    'prettier/prettier': true
  }
}

结尾

本文所涉及到的源代码, 作者已全部上传到自己的Github仓库fe-lint-tools中, 欢迎大家探讨