Eslint 配置共享

2022/7/9 Eslint安装配置

对于现在的项目来说,Eslint 基本上就是项目的标配之一。但有一点比较麻烦的就是,每次新建一个工程的时候都要安装一堆的依赖,然后再配置 .eslintrc 这类配置文件。直接用开源的某个插件可能配置又不是都满足需求,最后还是配置出来一个自己顺手的配置项,然后新项目又要重复再来一遍操作。

很明显上述操作是极其繁琐的,Eslint 提供了一个叫 Shareable Configs (opens new window) 的功能用来共享的 Eslint 配置信息,只要把某份配置好的配置信息做成一个 npm 模块就可以共享给其他人或者其他项目中下载使用这些配置。

# 创建配置模块

既然配置模块是一个常规的 npm 模块,那就依照 创建一个 Node.js 模块 (opens new window) 的步骤新建一个 npm 模块,模块名以 eslint-config- 开头,或者是 @scope/eslint-config 为前缀的模块名,比如 eslint-config-myconfig 或者 @scope/eslint-config@scope/eslint-config-myconfig

后续都是以 @fineorg/eslint-config-react (opens new window) 的实现为例进行说明。

mkdir eslint-config-react

cd eslint-config-react

npm init --scope=@fineorg
1
2
3
4
5

创建一个index.js文件,export一个Eslint的配置项。

module.exports = {
  rules: {
    semi: [2, "always"]
  }
};
1
2
3
4
5

文件中的配置项就和平时在.eslint.js配置文件中是一样的,引入plugins以及定义规则等都是支持的。

# 使用配置模块

为了确保config模块能够正常工作,需要在package.json中用 peerDependencies 字段声明依赖的 ESLint,推荐使用 “>=” 范围语法,即最低要求的 eslint 版本,声明该依赖以向后兼容。

"peerDependencies": {
  "eslint": "^8.0.0"
}
1
2
3

配置在设置完成后,先在本地试一下配置是否生效,看一下配置的效果。

# 在配置模块的目录下执行
# 把当前模块链接到全局中
npm link
1
2
3

模块发布后新建一个测试工程,然后在工程中安装一下看看是否生效。

# 创建一个测试工程
# npm 6.x
npm create vite@latest my-vue-app --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue

# 在测试工程安装
# 软链接到 node_modules 中,依赖不会提升到顶层
npm link @fineorg/eslint-config-react

# 会像真正安装一样把依赖提到顶层
# --install-links只有在以本地文件安装的时候才有用,如果直接以包名安装会从远端仓库找
npm install ../eslint-config-react --install-links
1
2
3
4
5
6
7
8
9
10
11
12
13

执行上述install之后会在package.json中添加依赖

"dependencies": {
  "@fineorg/eslint-config-react": "file:../eslint-config-react",
},
1
2
3

在测试工程eslint配置文件中使用config,就像引用网络上开源的其他config一样使用了,修改配置文件.eslintrc.json为

{
  "extends": "@fineorg/eslint-config-react"
}
1
2
3

如果配置模块可用且准备共享就可以发布到npm上了,建议使用eslinteslintconfig关键字方便其他人很容易的找到发布的模块。

# 多模块共享

一个配置模块还可以共享出不同的配置,使用的时候可以选择不同的配置,比如eslint:recommendedeslint:all这种。

最简单的实现方式就是使用不同的文件进行导出,比如在根目录下新建一个my-special-config.js文件并且到一个eslint的配置,可以通过如下方式访问

{
  "extends": "myconfig/my-special-config"
}
1
2
3

除了可以使用 Shareable Configs (opens new window) 来共享的配置之外,还可以使用 Configs in Plugins (opens new window) 达到相同的目的,不过这就属于 Eslint 的 Plugin 了。