Eslint使用记录

Configuring ESLint: https://eslint.bootcss.com/docs/user-guide/configuring

2022.3.16 星期三 17:00

配置

extends 和 plugins

extends

extends可以看做是集成一个个配置方案的最佳实践。它配置的内容实际就是一份份别人配置好的.eslintrc.js。

允许 extends 配置多个模块,如果规则冲突,位置靠后的包将覆盖前面的。rules 中的规则相同,并且优先级恒定高于 extends,类似class的extends,支持多继承。

1
2
3
4
5
extends: [ 
'eslint-config-myconfig', // 全称
//'myconfig' 缩写
'plugin:myplugin/recommended' // 插件中的 config
],

plugins

引入 plugin 可以理解为只是加载了插件,引入了额外的 自定义的rules。需要在 rules、extends 中定义后才会生效,如果没有则不生效。

plugin里不仅包括自定义的rules,还可以配置config,即总结的最佳实践,类似配置好的.eslintrc.js,因此这部分可以在extends里配置:plugin:config名称。

eslint的extends、plugin的区别

extends plugin
命名 eslint-config-或 @scope/eslint-config 或 @scope/eslint-config-myconfig eslint-plugin-<plugin-name>@scope/eslint-plugin-<plugin-name>
用途 集成一个个配置方案的最佳实践,即别人配置好的.exlintrc.js 必有:一堆自定义的规则的集合;可能有:总结的最佳实践
配置 全称:eslint-config-myconfig 缩写:myconfig插件中的config:plugin:plugin-name/config-name 如plugin:myplugin/recommended 全称:eslint-plugin-myconfig 缩写:myconfig

extends里的config和plugin里的config的区别

extends中的config
extends的一种命名规范
extends扩展名称格式必须为eslint-config-<name>

plugin中的config
plugin里的一个属性
用于配置一堆自定义的规则的集合

常用规则

问题

  1. eslint 'import' and 'export' may appear only with 'sourceType: module'
1
2
3
4
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
}

SMTC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

module.exports = {

parserOptions: {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
env: {
"browser": true,
"node": true,
"es6": true
},
globals: {
// "JD": "readonly",
},
extends: [
// "eslint:recommended",
// "@jd/eslint-config-jd",
"plugin:react/recommended",
// "taro/react"
],
rules: {}
}

plugins

eslint-config-taro

eslint-config-taro: https://www.npmjs.com/package/eslint-config-taro

Taro ESLint config,只有当 ESLint 规则全部都通过时,Taro 小程序端才可能正常运行。
npm install eslint babel-eslint eslint-config-taro eslint-plugin-taro eslint-plugin-react eslint-plugin-import --save-dev

在 .eslintrc 中设置:

1
2
3
4
5
{
"extends": [
"taro"
]
}

插件包含了四个方面的规则:

  • 自定义规则 (via eslint-plugin-taro)
  • 变量定义规则
  • import 规则 (via eslint-plugin-import)
  • JSX 规则 (via eslint-plugin-react)

eslint-plugin-taro

eslint-plugin-taro: https://www.npmjs.com/package/eslint-plugin-taro

规则
taro/custom-component-children
taro/if-statement-in-map-loop
taro/manipulate-jsx-as-array
taro/no-anonymous-function-in-props
taro/no-jsx-in-class-method
taro/no-jsx-in-props
taro/no-ref
taro/no-spread-in-props
taro/no-stateless-component

eslint-plugin-react

eslint-plugin-react: https://www.npmjs.com/package/eslint-plugin-react

eslint-plugin-import

eslint-plugin-import: https://www.npmjs.com/package/eslint-plugin-import

This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, and prevent issues with misspelling of file paths and import names. All the goodness that the ES2015+ static module syntax intends to provide, marked up in your editor.

knowledge is no pay,reward is kindness
0%