我们的 eslint-config 实践

2022-05-31 · 30min

背景

质量建设是今年事业部的工作重点之一,它很重要、相当重要。对于前端研发而言,目前代码规范很难得到一个统一的管控,各个项目里的 ESLint 都不一致,VSCode 里相关的配置也不尽相同。因此,有必要提出一个统一的 ESLint 规范配置并加以落实。 该规范配置命名为 @intelli-fe/eslint-config,之后可以通过 npm 安装。

该配置有一定的定制性,虽然看名字比较「普世」,但仅适用于 Vue3 + Ts。

团队注意:对于之后的新项目,强制执行;对于历史项目,酌情改造。

ESLint 相关疑问的厘清

ESLint 是什么

ESLint 是一个开源的 JavaScript 代码检查工具,由 Nicholas C. Zakas 于 2013 年 6 月创建。

提示:不管 TS 还是 JS,都用 ESLint,TSLint 已经不再维护了。

ESLint 的原理,简单记:

  1. 把非 js 文本处理成 js;
  2. 使用解析器把源码解析成 AST;
  3. 调用规则 rules,对 AST 进行检查,返回问题点;
  4. 对问题点进行处理(格式化提示、警告、报错等);
  5. 基于字符串替换实现 autoFix。

ESLint 和 Prettier 的区别

代码格式:单行代码长度、tab 长度、空格、逗号、分号等。

代码质量:未使用变量、三等号、全局变量声明等。

  • ESLint 的关注点是「代码格式」、「代码质量」。
  • Prettier 只关注「代码格式」。之前很流行,尤其是在 ESLint 不支持 autoFix 的时候。
  • 一个项目里,可以两者单独使用,也可以一起使用。

为减少心智负担,推荐之后只用 ESLint,不再用 Prettier。

ESLint 如何起作用

  • 通过命令行执行 lint。(常用于机器自动化)
  • 通过 IDE 进行 lint。(常用于人类 dev)

两者都需要配置信息,主要的配置方式有:

  1. 配置注释 - 在目标文件中使用注释语法嵌入配置信息。这种配置只对当前文件有效。比如 /* eslint-disable xxx */
  2. 配置文件 - 在 JavaScript、JSON 或 YAML 文件中定义配置信息。对配置文件所在目录的所有文件有效。 如果在同一个目录中有多个配置文件,则它们中间只有一个是有效的,优先级由高到低如下:
    1. .eslintrc.js
    2. .eslintrc.yaml
    3. .eslintrc.yml
    4. .eslintrc.json
    5. .eslintrc
    6. package.json(eslintConfig 字段)

.eslintrc 中 rules 的配置

  • off 或 0 - 关闭规则。
  • warn 或 1 - 开启规则,触发警告,程序不会退出。
  • error 或 2 - 开启规则,触发错误,程序退出。

例子:

// .eslintrc.js
module.exports = {
  rules: {
    'semi': [1, 'never'],
    'comma-dangle': ['error', 'always-multiline'],
    'vue/no-v-html': 0,
    'vue/component-name-in-template-casing': ['error', 'PascalCase']
  }
}

.eslintrc 中 plugins 和 extends 的区别

plugins

ESLint 的规则可以通过 rules 配置,例如:

// .eslintrc.js
module.exports = {
  rules: {
    indent: 'off'
  },
}

由于 ESLint 本身主要是对 js 代码进行语法检查以及少量代码格式化的操作,对于一些 ESLint 没有定义的规则或其他格式文件的内容就无法进行 lint 校验。此时,就需要使用 ESLint 提供的 plugins 插件配置对 lint 规则进行新增。一句话:为了增强 lint 规则。

例如 eslint-plugin-vue 这个 Vue 官方插件,可以对 vue 文件中的 <template> 和 <script> 内容进行检查。

需要:

1)安装它,pnpm i eslint-plugin-vue --dev;

2)加载并开启它。

// .eslintrc.js
module.exports = {
  plugins: [
    'vue', // 加载,写成 eslint-plugin-vue 亦可
  ],
  rules: {
    'vue/no-template-key': 1, // 开启,表示 template 标签上不能使用 key 属性,否则警告
  },
}

extends

plugins 与 rules 的结合是 ESLint 的基础能力,而 extends 可以看成是「集成一个个配置方案的最佳实践」。 它配置的内容实际就是一份份别人配置好的 .eslintrc.js。

还是以 eslint-plugin-vue 为例,它实现了上百种配置规则,为了方便其他人使用,它默认实现了几种最佳实践:

module.exports = {
  configs: {
    'base': require('./configs/base'),
    'essential': require('./configs/essential'),
    'no-layout-rules': require('./configs/no-layout-rules'),
    'recommended': require('./configs/recommended'),
    'strongly-recommended': require('./configs/strongly-recommended'),
    'vue3-essential': require('./configs/vue3-essential'),
    'vue3-recommended': require('./configs/vue3-recommended'), // 咱们一般用这个
    'vue3-strongly-recommended': require('./configs/vue3-strongly-recommended')
  },
}

这样就可以直接把官方配置好的最佳实践拿来用。如果碰到和自己风格或者规范有冲突的规则,直接在 rules 中重新定义就可以了。

// .eslintrc.js
module.exports = {
  extends: [
    'plugin:vue/vue3-recommended',
  ],
  rules: {
    'vue/no-v-html': 'off', // 官方默认是 'warn'
  },
}

.eslintrc 的一些其他配置

env

用于定义项目代码运行的环境,因为每个环境都带有一组特定的预定义全局变量。

在咱们目前的项目里,一般只需指定 browser、node、es6 即可。

// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    node: true,
    es6: true,
  },
}

globals

如果在代码中调用了某些全局变量,而全局变量却并没有在当前页面中引入,这样就会造成 ESLint 检测时提示错误。

把全局变量配置到 globals 对象中作为键,值可以设置为 writable、readonly 或 off。

  • writable 指这个全局变量可以被重新赋值修改。
  • readonly 表示这个全局变量只可读,不允许重新赋值修改。
  • off 表示这个全局变量不可用,ESLint 如果检测到,就会报错提示。

关于 off 举个🌰——在某个环境下只能使用大多数 ES2015 全局变量,但 Promise 对象不可以使用,因此项目代码就不允许出现 Promise 对象,若出现 ESLint 须报错。此时可以如下配置:

// .eslintrc.js
module.exports = {
  env: {
    es6: true,
  },
  globals: {
    Promise: 'off',
  },
}

parser

用于定义 ESLint 的解析器,ESLint 通过解析器去解析代码并进行代码校验,默认解析器是 Espree,如果我们需要自定义其他解析器让,就需要把解析器配置到 parser。

我们目前用的比较多的解析器:

  • @typescript-eslint/parser:可以将 TypeScript 进行转换并解析。
  • vue-eslint-parser:可以解析 Vue 单文件,允许去校验其中 <template> 的内容格式。当使用该解析器时,允许我们在 parserOptions.parser 去定义 .vue 文件的 <script> 内容解析器。比如:
    module.exports = {
      parser: 'vue-eslint-parser',
      parserOptions: {
        parser: '@typescript-eslint/parser',
      },
    }

@intelli-fe/eslint-config 介绍

特点

  • 无需 Prettier。
  • 无需 .eslintignore。
  • 支持 ES、TS、Vue3、JSON、YAML、Markdown。

提示:如果是 Vue2.x 项目,可使用 @intelli-fe/eslint-config-vue2。

一些值得注意的 rules

  • Object、Array 中存在多行时,最后一行需要加逗号。

    // 规则
    "comma-dangle": ['error', 'always-multiline'],
    "@typescript-eslint/comma-dangle": ['error', 'always-multiline'],
    "vue/comma-dangle": ['error', 'always-multiline']
    
    // 例子 - Good
    const foo = {
      bar: 'baz',
      qux: 'quux',
    }
    
    const foo = { bar: 'baz', qux: 'quux' }
    const arr = [1, 2]
    
    const arr = [1,
      2]
    
    const arr = [
      1,
      2,
    ]
    
    foo({
      bar: 'baz',
      qux: 'quux',
    })
  • 文件中不能有超过 1 行空行,文件开头不能有空行,文件结尾应该为 1 个空行。

    // 规则
    {
      "eol-last": "error",
      "no-multiple-empty-lines": [
        "error",
        { "max": 1, "maxBOF": 0, "maxEOF": 1 }
      ]
    }
  • 空格的规范,不能没有,也不能有多余。

    // 规则
    '@typescript-eslint/space-infix-ops': 'error',
    'vue/space-infix-ops': 'error',
    'no-multi-spaces': 'error'
    
    // 例子 - Bad
    const foo =  '1'
    const foo ='1'
    import { a,  b }from 'xxx'
    
    // 例子 - Good
    const foo = '1'
    import { a, b } from 'xxx'
  • import 中的变量要按规则排序。

    // 规则
    'sort-imports': [
      'error',
      {
        ignoreCase: false,
        ignoreDeclarationSort: true,  // 默认为 false
        ignoreMemberSort: false,
        memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
        allowSeparatedGroups: false,
      }
    ]
    
    // 例子 - Bad
    import { b, a } from 'xxx'
    
    import a from 'xxx'
    import { b, c } from 'xxx'
    import * as d from 'xxx'
    import 'xxx'
    
    // 例子 - Good
    import 'xxx'                  // none
    import * as d from 'xxx'      // all
    import { b, c } from 'xxx'    // multiple
    import a from 'xxx'           // single
  • if、else-if、else、for、while、do,在只有 1 行语句时,不需要有花括号。且 if、else-if、else 中的括号规则要保持一致。

    // 规则
    'curly': ['error', 'multi-or-nest', 'consistent']
    
    // 例子 - Bad
    if (true) {
      foo()
    }
    
    // 例子 - Good
    if (true)
      foo()
    else
      baz()
    
    if (foo) {
      bar()
    } else if (faa) {
      bor()
    } else {
      other()
      things()
    }
    
    while (true)
      doSomething()
    
    for (var i = 0; foo; i++)
      doSomething()
  • 其他规则,大家慢慢试吧,总之很规范就对了。

安装及使用

安装

pnpm add -D eslint @intelli-fe/eslint-config

使用

配置 package.json,添加 @intelli-fe/eslint-config 和 eslint。

{
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  },
  "devDependencies": {
    "@intelli-fe/eslint-config": "^1.0.0",
    "eslint": "^8.15.0"
  }
}

添加 .eslintrc.xx。

{
  "extends": "@intelli-fe"
}

使用 VSCode 时,为了「保存时自动 lint」,在项目根目录添加 .vscode/settings.json 文件,编写配置。(好用哦 :yum:)

{
  "prettier.enable": false,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

来一个 Demo 演示

如何编写的

采用 pnpm 的 monorepo,参见代码结构。

如何发布的

  1. npm 官网注册用户。 我有一个个人账户,同时也注册了一个组织账户——intelli-fe,用来发布咱们前端的公共包,大家可以一起维护,或者在 @intelli-fe 下发布其他包。

    说明:现在很多 package 都会带上 scope,比如 @vue、@ant-design、@vitejs 等,当你注册一个个人账户或组织账户时,npm 就会允许你使用用户名/组织名来命名 scope,类似于命名空间,防止和其他人/组织的包发生冲突。

  2. 本地登录(命令行)。

    # 首次
    npm adduser
    
    # 之后
    npm login

    每次都要输入用户名、密码、邮箱、OTP,如果开启了 2FA(双因子认证),则不需要输入 OTP。但是开启 2FA 比较麻烦。

  3. 发布

    npm publish --access public

    因为有 scope 的缘故,所以它默认是 private(公共无法访问)。要想让这个包被公共访问,需要在命令行加上 --access public。 npm 和 github 不一样,如果要想发布 private 的包,需要花钱。

注意:如果大家用的是淘宝的 npm 镜像,需要在 adduser、login、publish 命令后面加上 --registry https://registry.npmjs.org。

如果遇到报错,网上搜索解决。肯定会遇到报错的 🙃。


完。