你不能再说你不会配置ESLint和prettier了

2,845

为了更直观的体验,我这里就从头创建了一个新的项目来配置eslint等相关配置,这里就跳过项目初始化步骤

ps: 本文全篇采用pnpm来当包管理器,有些命令可能与npm 不同

ps: 如果你使用的是vsCode, 那么强烈建议你安装 eslint prettier styleLint相关的代码格式化插件, 提升开发幸福感 如果你对eslint还有点生疏,请看我这篇文章ESLint各个配置详解-plugins/rules/extends

eslint

第一步 先安装 eslint

    pnpm add eslint -D

然后使用命令行工具进行eslint配置文件的初始化

    pnpm create @eslint/config
    # or
    npm init @eslint/config

然后就会有交互式选项跟着提示一步步回车就好,

使用ESLint做什么? 我选择第三个

    ? How would you like to use ESLint? ...
      To check syntax only  // 仅检查语法
      To check syntax and find problems  // 检查语法并发现问题
    > To check syntax, find problems, and enforce code style // 检查语法、发现问题并强制执行代码样式

接下来询问你在哪种项目模块规范中使用, 我选择第一个

    ? What type of modules does your project use? ...
    > JavaScript modules (import/export)
      CommonJS (require/exports)
      None of these

接下来询问在哪个框架中使用, 我这里使用vue做demo演示,

        ? Which framework does your project use? ...
          React
        > Vue.js
          None of these
          

接下来会询问你是否使用ts和代码在哪里运行,我这里选择 是和两个运行环境都选择

        √ Does your project use TypeScript? · No / **Yes**
        √ Where does your code run? · browser, node

然后问你希望如何定义项目的样式, 这里看你实际需要,因为后面我还要配置pretter, 我选的第二个

        √ How would you like to define a style for your project? …
          Use a popular style guide
        ❯ Answer questions about your style
        ## next
        √ How would you like to define a style for your project? · prompt

然后询问你想用什么格式的配置文件, 看过我上篇文章的应该就了解了, 我选择js

        ? What format do you want your config file to be in? ...
        > JavaScript
          YAML
          JSON

询问缩进风格,我喜欢用tab键, 看你们习惯选择就好, 后期可以设置是4个还是2个空格为一次缩进

        ? What style of indentation do you use? ...
        > Tabs
          Spaces

字符串使用双引号还是单引号? 我项目组里的喜欢单引号

        ? What quotes do you use for strings? ...
          Double
        > Single

用哪种结束符? WindowsCRLF, UnixLF, 我选Unix

        ? What line endings do you use? ...
        > Unix
          Windows

用分号吗? 我们项目组习惯有 我这里选的yes

? Do you require semicolons? » No / Yes

然后它会提示你需要安装下面的哪些依赖

        @typescript-eslint/eslint-plugin@latest eslint-plugin-vue@latest @typescript-eslint/parser@latest
        ? Would you like to install them now? » No / Yes   

我记得以前好像默认使用npm下载,我一般习惯用pnpm,所以都默认false,自己后面手动安装,但eslint新版本更新了? 这段时间发现我选择是之后会让我选包管理工具,点赞

        @typescript-eslint/eslint-plugin@latest eslint-plugin-vue@latest @typescript-eslint/parser@latest
        ? Would you like to install them now? » No / Yes    

        ? Which package manager do you want to use? ...
          npm
          yarn
        > pnpm 

随后安装完依赖就会在项目的跟目录下生成.eslintrc.js文件

image.png 然后找个文件点进去看就会发现eslint已经生效了

image.png 然后建议大家新增一个eslint的忽略文件.eslintignore, 忽略一个文件或者文件夹的检查,大家根据自身实际情况配置就好


*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
Dockerfile

然后, 我们会对里面的配置进行一系列调整

Prettier

虽然 ESLint 本身具备自动格式化代码的功能(eslint --fix),但术业有专攻,ESLint 的主要优势在于代码的风格检查并给出提示,而在代码格式化这一块 Prettier 做的更加专业,因此我们经常将 ESLint 结合 Prettier 一起使用。

安装prettier

    pnpm add prettier -D

在项目根目录新建.prettierrc.js配置文件,填写如下的配置内容:

其他的配置可去官网查看www.prettier.cn/docs/option…

    // .prettierrc.js
    module.exports = {
      printWidth: 100, //一行的字符数,如果超过会进行换行,默认为80
      tabWidth: 4, // 一个 tab 代表几个空格数,默认为 2 个
      useTabs: false, //是否使用 tab 进行缩进,默认为false,表示用空格进行缩减
      singleQuote: true, // 字符串是否使用单引号,默认为 false,使用双引号
      semi: true, // 行尾是否使用分号,默认为true
      trailingComma: "none", // 是否使用尾逗号
      htmlWhitespaceSensitivity: "strict", // HTML空白敏感度
      bracketSpacing: true, // 对象大括号直接是否有空格,默认为 true,效果:{ a: 1 }
      proseWrap: "never", // 换行设置
    };

然后也可在根目录下新建.prettierignore文件, 内容如下

    /dist/*
    .local
    .output.js
    /node_modules/**

    **/*.svg
    **/*.sh

    /public/*

ps: 也可以不创建, 我觉的有.eslintignore就够了

然后 可以在命令行执行 npx prettier -w . 就会使用prettier格式化所有文件

接下来,将prettier与eslint结合起来,安装下面两个依赖

pnpm i eslint-config-prettier eslint-plugin-prettier -D

eslint-config-prettier用来覆盖 ESLint 本身的规则配置,

eslint-plugin-prettier则是用于让 Prettier 来接管eslint --fix即修复代码的能力。

最终调整完得代码如下

    // .eslintrc.js
    module.exports = {
        env: {
            browser: true,
            es2021: true,
            node: true
        },
        extends: [
            'plugin:@typescript-eslint/recommended',
            'plugin:vue/vue3-recommended',
            'plugin:prettier/recommended'
        ],
        // 参考vue官方推荐,替换默认parser
        parser: 'vue-eslint-parser',
        parserOptions: {
            ecmaVersion: 'latest',
            ecmaFeatures: {
                jsx: true
            },
            parser: '@typescript-eslint/parser',
            sourceType: 'module'
        },
        plugins: ['@typescript-eslint', 'vue'],
        rules: {
            indent: ['error', 4],
            'linebreak-style': ['error', 'unix'],
            quotes: ['error', 'single'],
            semi: ['error', 'always']
        }
    };
    

plugin:prettier/recommended它相当于以下配置:来自官方文档说明

    module.exports = {
      extends: ["prettier"],
      plugins: ["prettier"],
      rules: {
        "prettier/prettier": "error",
        "arrow-body-style": "off",
        "prefer-arrow-callback": "off",
      },
    };

然后我们回到项目中来见证一下ESLint + Prettier,在 package.json 中定义一个脚本:

    {
      "scripts": {
        "lint:script": "eslint --ext .js,.jsx,.ts,.tsx --fix --quiet ./",
      }
    }

这个命令如果你安装了vscode得插件 eslint和pretieer, 就不太需要了,会自动格式化了

去设置保存自动格式化

大家注意设置得时候我标记的地方

  1. 是到setting.json中去配置;
  2. 针对全局,所有项目通用;
  3. 针对当前工作区,也就是当前项目生效,会在项目得根目录生成.vsecode文件夹,里面会有setting.json文件

Stylelint

Stylelint,一个强大的现代化样式 Lint 工具,用来帮助你避免语法错误和统一代码风格。

虽然prettier对代码风格格式化已经很专业了,但stylelint在针对样式文件方面更专业, 当然这部也可省略

它的强大之处在于:

  • 具有 100 多个用于现代 CSS 语法和功能的内置规则
  • 支持插件,因此您可以创建自己的自定义规则
  • 尽可能自动修复问题
  • 支持可创建或扩展的可共享配置
  • 可根据您的确切需求进行定制
  • 具有 15k 单元测试使其健壮
  • 受到谷歌和GitHub等全球公司的信赖

首先让我们来安装 Stylelint 以及相应的工具套件:

pnpm i stylelint stylelint-prettier stylelint-config-prettier stylelint-config-recess-order stylelint-config-standard stylelint-config-standard-scss -D

然后新建.stylelintrc.js文件 开始编写配置

// .stylelintrc.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,
    'no-duplicate-selectors': null
  }
};

一些其他配置可以参考stylelint官网

接下来我们将 Stylelint 集成到项目中,回到 package.json 中,增加如下的 scripts 配置:

{
  "scripts": {
    // 整合 lint 命令
    "lint": "npm run lint:script && npm run lint:style",
    // stylelint 命令
    "lint:style": "stylelint --fix "src/**/*.{css,scss}""
  }
}

但你安装了之前说的vscode插件是一般用不到这两个命令的,在开发阶段就会提示代码格式问题,提前进行修复。

完整配置

到这里其实eslint + prettier就已经配置完了,下面贴一下完整配置

    // .eslintrc.js
    module.exports = {
        env: {
            browser: true,
            es2021: true,
            node: true
        },
        extends: [
            'plugin:@typescript-eslint/recommended',
            'plugin:vue/vue3-recommended',
            'plugin:prettier/recommended'
        ],
        parser: 'vue-eslint-parser',
        parserOptions: {
            ecmaVersion: 'latest',
            ecmaFeatures: {
                jsx: true
            },
            parser: '@typescript-eslint/parser',
            sourceType: 'module'
        },
        plugins: ['@typescript-eslint', 'vue'],
        rules: {
            indent: ['error', 4],
            'linebreak-style': ['error', 'unix'],
            quotes: ['error', 'single'],
            semi: ['error', 'always'],
            // vite打包时自动去除console和debugger,所以这里直接关掉检查
            'no-console': 'off',
            'no-debugger': 'off'
        }
    };

    // .prettierrc.js
    module.exports = {
        printWidth: 100, //一行的字符数,如果超过会进行换行,默认为80
        tabWidth: 4, // 一个 tab 代表几个空格数,默认为 2 个
        useTabs: false, //是否使用 tab 进行缩进,默认为false,表示用空格进行缩减
        singleQuote: true, // 字符串是否使用单引号,默认为 false,使用双引号
        semi: true, // 行尾是否使用分号,默认为true
        trailingComma: 'none', // 是否使用尾逗号
        htmlWhitespaceSensitivity: 'strict', // HTML空白敏感度
        bracketSpacing: true, // 对象大括号直接是否有空格,默认为 true,效果:{ a: 1 }
        proseWrap: 'never' // 换行设置
    };

大家针对项目实际情况,再对规则进行调整就好了

我安装的依赖及版本号

     "devDependencies": {
            "@typescript-eslint/eslint-plugin": "^5.59.8",
            "@typescript-eslint/parser": "^5.59.8",
            "eslint": "^8.41.0",
            "eslint-config-prettier": "^8.8.0",
            "eslint-plugin-prettier": "^4.2.1",
            "eslint-plugin-vue": "^9.14.1",
            "prettier": "^2.8.8",
            "stylelint": "^15.6.2",
            "stylelint-config-prettier": "^9.0.5",
            "stylelint-config-recess-order": "^4.0.0",
            "stylelint-config-standard": "^33.0.0",
            "stylelint-config-standard-scss": "^9.0.0",
            "stylelint-prettier": "^3.0.0",
        }

下一篇: Husky 和 Lint-staged 入门指南

系列文章

系列1 Eslint各个配置详解-plugins/rules/extends
系列2 怎么配置ESLint和prettier
系列3: Husky 和 Lint-staged 入门指南
git仓库地址 github.com/Miaodashu/e…