Article Directory
One, eslint
eslint is a front-end js static code inspection tool that helps us standardize the code and find some potential bugs
Official instructions: https://eslint.org/
Two, installation
Ensure that the node environment has been installed
1. Install the dependency package eslint
npm install eslint --save-dev
2. Set up the package.json file
"scripts":{
...
"lint":"eslint src",
"lint:create":"eslint --init"
}
3. Initialize eslint
In this example, the react project is taken as an example, vue or other projects can be selected according to the prompts
npm run lint:create
The default selection is fine
After creation, the .eslintrc.js file will appear in the root directory
.eslintrc.js
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
}
};
4. Check the code
npm run lint
The fifth character in line 2, the error rule is no-unused-vars, and the variable has not been used
. The 13th character in line 3, the error rule is no-undef, and the variable is not defined in the
eslint rule table. See http://eslint. cn/docs/rules/
Three, the problems encountered
1.‘xxx‘ is missing in props validation
'xxx' is missing in props validation and component variables is assigned a value but never used
You can configure the rules you want in the rules of the .eslintrc.js file to solve
"rules": {
"react/prop-types": 0 //防止在react组件定义中缺少props验证
}
2.Using this.refs is deprecated
Using this.refs is deprecated
Using string literals in ref attributes is deprecated
Solution:
Modify the definition of ref, and the place of use.
Original:
html:
<div ref="testDiv" />
js:
const div = this.refs.testDiv;
change into:
html:
<div ref={(v) => { this.testDiv = v; }} />
js:
const div = this.testDiv;
The reason is: the official has changed the (recommended) use of ref to be called by string and changed it to the form of a callback function.
3. More rules configuration:
"rules": {
"eqeqeq": 2, //必须使用 === 和 !==
"no-empty-function": 2, //禁止空函数
"no-multi-spaces": 2, //禁止使用多个空格
"no-trailing-spaces": 2, //禁止禁用行尾空格
"space-infix-ops": 2, // 要求操作符周围有空格
"space-in-parens": 2, //强制在圆括号内使用一致的空格
"no-var":2, //要求使用 let 或 const 而不是 var,
"no-unused-vars": 2, //禁止出现未使用过的变量
"react/prop-types": 0 //防止在react组件定义中缺少props验证
}
Link to this article: https://blog.csdn.net/qq_39903567/article/details/115294455