给 React + TS 项目添加 ESLint + Prettier,附注意事项及文档

ESLint 用于发现代码错误,统一代码风格。

Prettier 专门用来美化格式、统一代码风格,在这个方面比 ESLint 更强大。

它们真的很香

本文记录一下我给一个项目添加 ESLint + Prettier 的过程,以及遇到的问题和注意的点。

项目是 ts + react 开发的组件库,样式使用 scss,通过 webpack4 打包。

安装配置 ESLint

安装需要的包

分开写,更清晰:

npm i eslint -D
npm i @typescript-eslint/parser @typescript-eslint/eslint-plugin -D
npm i eslint-plugin-react -D
npm i eslint-config-alloy -D
npm i eslint-loader -D
  • 首先要安装 eslint,eslint 默认使用 Espree 进行解析,无法识别 ts 的一些语法,所以需要安装一个 ts 的解析器 @typescript-eslint/parser,用它来代替默认的解析器,然后由 @typescript-eslint/eslint-plugin 来提供有关 ts 的规则补充。
  • 由于是 react 项目,所以还需要插件 eslint-plugin-react 来支持 .tsx
  • eslint 规则众多,且有些原生规则在 ts 中不兼容,推荐 alloy 的这套配置 eslint-config-alloy,它提供了 ts + react 的版本,并且不包含代码格式的部分,与 Prettier 完全兼容。
  • 最后是提供给 webpack 的 eslint-loader,可以在使用 webpack-dev-server 开发中实时检查,越早发现错误越好解决。

写配置文件

接下来在项目根目录创建 .eslintrc.json 文件

{
    "parser": "@typescript-eslint/parser",
    "plugins": [
        "@typescript-eslint/eslint-plugin"
    ],
    "extends": [
        "alloy",
        "alloy/react",
        "alloy/typescript"
    ],
    "settings": {
        "react": {
            "version": "detect"
        }
    },
    "env": {
        // 您的环境变量(包含多个预定义的全局变量)
        // Your environments (which contains several predefined global variables)
        //
        // browser: true,
        // node: true,
        // mocha: true,
        // jest: true,
        // jquery: true
    },
    "globals": {
        // 您的全局变量(设置为 false 表示它不允许被重新赋值)
        // Your global variables (setting to false means it's not allowed to be reassigned)
        //
        // myGlobal: false
    },
    "rules": {
        // 自定义您的规则
        // Customize your rules
    }
}

如上,把解析器、插件、扩展的规则集都配置进去。

添加script指令

package.jsonscripts 中添加指令,就可以使用了

// package.json

{
    "scripts": {
        "lint": "eslint '{components,example}/**/*.{ts,tsx,js,jsx}'",
        "lint_fix": "eslint '{components,example}/**/*.{ts,tsx,js,jsx}' --fix"
    }
}

以上指令表示对 componentsexample 文件夹下的 .ts.tsx.js.jsx 文件进行检查。

上面是 glob 的形式,也可以像下面这样写成文件夹形式,就需要通过 --ext 来对扩展的文件类型进行指定。

// package.json

{
    "scripts": {
        "lint": "eslint {components,example} --ext .ts,.tsx,.js,jsx",
        "lint_fix": "eslint {components,example} --ext .ts,.tsx,.js,jsx --fix"
    }
}

注意:

glob 形式下文件路径要加引号。

--ext 只能搭配文件夹形式,对 glob 形式无效。

给 webpack 添加 eslint-loader

module: {
        rules: [
            {
                test: /\.(jsx|js|ts|tsx)$/,
                include: [
                    path.resolve(__dirname, '../components'),
                    path.resolve(__dirname, '../example')
                ],
                exclude: [/node_modules/],
                use: ['eslint-loader'],
                enforce: 'pre'
            }
      ]
}

注意:

要把它放在 rules 的第一项,或者添加 enforce: 'pre' 来保证首先应用 eslint-loader,因为是要对我们的源代码进行检查,检查要在 babel-loader 等其他编译之前。

安装 vscode 的 eslint 插件

插件中搜 eslint 直接安装,就可以在编辑器拥有实时错误标红。

然后在 settings.json 中添加:

"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }

就可以在保存文件时自动 fix。

怎么打开 settings.json ?左下角齿轮 -> 第一行 command ... -> 输入 open settings.json

添加 .eslintignore 文件

编辑器中的检测没有指定路径,所以会检查 componentsexample 之外的文件,如果有些不想让它检查,可以根目录添加 .eslintignore 文件。

build/
dist/

默认包含 node_modules/

ESLint 就配置好了,包括 配置文件 + 执行脚本 + webpack + 编辑器。

安装配置 Prettier

安装 Prettier 包

npm i prettier -D

新建 prettier.config.js 文件配置规则

prettier 的配置规则很少,推荐一套作为参考。

// prettier.config.js or .prettierrc.js
module.exports = {
    // 一行最多 100 字符
    printWidth: 100,
    // 使用 4 个空格缩进
    tabWidth: 4,
    // 不使用缩进符,而使用空格
    useTabs: false,
    // 行尾需要有分号
    semi: true,
    // 使用单引号
    singleQuote: true,
    // 对象的 key 仅在必要时用引号
    quoteProps: 'as-needed',
    // jsx 不使用单引号,而使用双引号
    jsxSingleQuote: false,
    // 末尾不需要逗号
    trailingComma: 'none',
    // 大括号内的首尾需要空格
    bracketSpacing: true,
    // jsx 标签的反尖括号需要换行
    jsxBracketSameLine: false,
    // 箭头函数,只有一个参数的时候,也需要括号
    arrowParens: 'always',
    // 每个文件格式化的范围是文件的全部内容
    rangeStart: 0,
    rangeEnd: Infinity,
    // 不需要写文件开头的 @prettier
    requirePragma: false,
    // 不需要自动在文件开头插入 @prettier
    insertPragma: false,
    // 使用默认的折行标准
    proseWrap: 'preserve',
    // 根据显示样式决定 html 要不要折行
    htmlWhitespaceSensitivity: 'css',
    // 换行符使用 lf
    endOfLine: 'lf'
};

执行检查

npx prettier --test .  // 全部文件
npx prettier --test components/  // 特定文件

执行修复

npx prettier --write .  // 全部文件
npx prettier --write components/  // 特定文件

安装 vscode 的插件,自动格式化

实际上不用执行,直接安装编辑器插件,保存文件就直接自动格式化了。

vscode 搜 prettier 直接安装,然后在 settings.json 中添加配置:

"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"

遇到的问题

1.eslint 匹配不到文件会报错

刚开始 eslint 总是会报错

Oops! Something went wrong! ????

ESLint: 7.5.0

No files matching the pattern "node_modules/asn1.js" were found.

Please check for typing mistakes in the pattern.

然后发现是因为没有匹配到文件,就报错了。。

可以添加 flag --no-error-on-unmatched-pattern 禁止这种报错。

2.tsllint 已弃用

tslint 已经于2019年1月就不再维护,并提供到 typescript-eslint 的迁移,可以说 typescript-eslint 是目前支持 ts 的首选 lint。

3.prettier 不支持缩进语法的 css 预编译语言

prettier 支持非常多的文件类型,目前为止官网支持的文件如下

  • JavaScript (including experimental features)
  • JSX
  • Angular
  • Vue
  • Flow
  • TypeScript
  • CSS, Less, and SCSS
  • HTML
  • JSON
  • GraphQL
  • Markdown, including GFM and MDX
  • YAML

要注意的是,对于样式它和 stylelint 一样,不支持缩进格式风格的.sass.styl

最后附上文档地址

eslint rules: https://eslint.org/docs/rules/

eslint rules 中文: http://eslint.cn/docs/rules/

typescript-eslint rules

prettier 文档: https://prettier.io/docs/en/index.html

typescript代码检查: https://ts.xcatliu.com/engineering/lint.html