A, eslint

Eslint is a front-end JS static code checker that helps us normalize code and find potential bugs

Official instructions: https://eslint.org/

Second, the installation

Ensure that the Node environment is installed

1. Install the dependency package esLint

npm install eslint –save-dev

2. Set package.json file

"scripts":{
    ...
    "lint":"eslint src",
    "lint:create":"eslint --init"
}
Copy the code

3. Initialize ESLint

The React project is used as an example. Select vUE or other projects as prompted

npm run lint:create
Copy the code

Default is ok

The.eslintrc.js file will appear after the root directory is created

.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": {
    }
};

Copy the code

4. Check the code

npm run lint

Line 2 5 characters, error rule to no – unused – vars, variable has not been used line 3 characters, 13 rules of error to no – undef, variable is not defined eslint rule table look at http://eslint.cn/docs/rules/

3. Problems encountered

1. ‘XXX’ is missing in props Validation

‘XXX’ is missing in props Validation and component variable is assigned a value but never used

To solve this problem, you can configure the desired rules in the rules file of.eslintrc.js

"Rules ": {"react/prop-types": 0 // prevent lack of props validation in react component definitions}Copy the code

2.Using this.refs is deprecated

Using this.refs is deprecated
Using string literals in ref attributes is deprecated
Copy the code

Solution: Modify the definition of ref, and use where originally:

html:
<div ref="testDiv" />
js:
const div = this.refs.testDiv;
Copy the code

Is amended as:

html:
<div ref={(v) => { this.testDiv = v; }} />
js:
const div = this.testDiv;
Copy the code

The reason: ref has been officially changed from a string call to a callback function.

3. More rules configuration:

"Rules ": {"eqeqeq": 2, // must use === and! == "no-empty-function": 2, // Disallow empty functions "no-multi-spaces": 2, // disallow multiple Spaces "no-trailing Spaces ": 2, // disallow disabling end-of-line space "space-infix-ops": 2, // require space around operator "space-in-parens": 2, // enforces consistent Spaces in parentheses "no-var":2, // requires let or const instead of var, "no-unused-vars": 2, // disallows unused variables "react/prop-types": 0 // Prevent the lack of props validation in react component definitions}Copy the code