Skip to content

ESLint + Prettierrc 代码质量检查与格式化

ESLint

用于代码质量检查、代码格式化,检测代码中潜在的错误并进行一些简单的修复。

示例基于 TypeScript

安装

安装 ESLintTypeScript 需要的工具

--save-dev 表示将依赖包安装为开发依赖(devDependency)

bash
npm install --save-dev eslint @eslint/js typescript typescript-eslint

说明

ESLint v9.0.0版本后,默认使用平面配置文件( eslint.config.js)取缔了 .eslintrc文件 如果是旧版本配置迁移更新时需要做如下处理:

  1. 删除 .eslintrc文件
  2. 移除 @typescript-eslint/parser@typescript-eslint/eslint-plugin插件依赖包,他们已经包含在 typescript-eslint
bash
npm un @typescript-eslint/parser @typescript-eslint/eslint-plugin

配置

在项目根目录创建一个 eslint.config.js配置文件

bash
touch eslint.config.js

添加如下配置(更多配置可参考官方文档,例如添加更严格的类型判断等):

typescript
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.recommended,
);

配置忽略(或不忽略)文件, ESLint 在检查时忽略这些文件或子文件夹

typescript
export default [
    {
        ignores: [
            "!node_modules/",           // unignore `node_modules/` directory
            "node_modules/*",           // ignore its content
            "!node_modules/mylibrary/"  // unignore `node_modules/mylibrary` directory
        ]
    }
];

运行 ESLint

在项目根目录中运行下面命令

bash
npx exlint .

或者在 package.json设置, 然后执行 npm run lint

javascript
{
    "scripts": {
        "lint": "eslint ."
    },
}

Prettier

用于代码格式化,关注代码预定的风格;在团队开发中,保证统一的代码风格。

安装

--save-exact 表示安装一个明确的版本号,即无 "^"

bash
npm install --save-dev --save-exact prettier

配置

在项目根目录新建 .prettierrc配置文件

bash
touch .prettierrc

在配置文件中添加配置,如:

json
{
    "trailingComma": "es5",
    "tabWidth": 4,
    "semi": false,
    "singleQuote": true
}

配置 .prettierignore文件,在格式化时会忽略掉配置文件里的文件或者目录

如下,在格式化时会忽略 build目录

bash
# Ignore artifacts:
build

运行 Prettier

使用 Prettier 格式化所有文件

格式化并修正覆盖

bash
npx prettier . --write

仅检查格式化

bash
npx prettier . --check

通过 VS Code 进行格式化

安装 VS Code 扩展 Prettier - Code formatterPrettier - Code formatter - Visual Studio Marketplace

在项目根目录中新增 .vscode/setting.json 配置文件添加代码(更多配置可参考官方文档)

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

预期情况下在修改源码保存后会自动的进行代码格式化

处理 ESLint 和 Prettier 冲突

🫣 在同时使用 PrettierESLint 是会存在冲突,因为 ESLint 也存在代码格式化的功能。 在项目中我们只想Prettier 进行格式化, ESLint 捕获错误,可以使用 eslint-config-prettier插件来处理冲突问题。 同时可使用 eslint-plugin-prettier 插件将 Prettier 作为 ESLint的规则(rules)

安装

bash
npm install --save-dev eslint-plugin-prettier eslint-config-prettier
# 如果已安装 prettier 请忽略下面这行
npm install --save-dev --save-exact prettier

配置将 Prettier 作为 ESLint 规则来使用

typescript
const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');

module.exports = [
  // Any other config imports go at the top
  eslintPluginPrettierRecommended,
];

配置完后

  1. 使用 prettier做进代码格式化
  2. 禁用 ESLint 中的 arrow-body-styleprefer-arrow-callback 规则(具体原因:GitHub - prettier/eslint-plugin-prettier: ESLint plugin for Prettier formatting
  3. 启用 eslint-config-prettier 配置,关闭与 Prettier 冲突的 ESLint 规则。

完整的配置示例

typescript
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'
import eslint from '@eslint/js'
import tseslint from 'typescript-eslint'

export default tseslint.config(
    eslint.configs.recommended,
    ...tseslint.configs.recommendedTypeChecked,
    ...tseslint.configs.stylisticTypeChecked,
    eslintPluginPrettierRecommended,
    {
        plugins: {
            '@typescript-eslint': tseslint.plugin,
        },
        languageOptions: {
            parser: tseslint.parser,
            parserOptions: {
                project: true,
            },
        },
        rules: {
            '@typescript-eslint/no-unsafe-argument': 'error',
            '@typescript-eslint/no-unsafe-assignment': 'error',
            '@typescript-eslint/no-unsafe-call': 'error',
            '@typescript-eslint/no-unsafe-member-access': 'error',
            '@typescript-eslint/no-unsafe-return': 'error',
        },
        ignores: [
            '!node_modules/', // unignore `node_modules/` directory
            'node_modules/*', // ignore its content
            '!node_modules/mylibrary/', // unignore `node_modules/mylibrary` directory
        ],
    }
)

备注:

配置过程中遇到的报错:

  1. 执行 npm run lint报错
bash
> [email protected] lint
> eslint .

(node:50023) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

如是使用了 ES 模块语法,在 package.json 添加

json
{
  "type": "module"
}
  1. VS Code配置完 Perttier不生效

尝试重新加载 VS Code,仍报错可以查看下具体的报错原因进行解决

参考资料

以上内容均来自官方文档,更多配置可以参考以下官方文档: Documentation - ESLint - Pluggable JavaScript LinterWhat is Prettier? · PrettierGetting Started | typescript-eslint

Released under the MIT License.