Basic use of ESLint

Meet ESLint

The purpose of linstatic is to avoid errors in the code when we run the code. The purpose of linstatic is to ensure that the code of linstatic can be analyzed uniformly without the help of linstatic, Maintain a consistent code style and improve the readability and maintainability of the code.

ESLint is similar to JSLint and JSHint before. It is a tool for static analysis and inspection of js code.

Using ESLint in command line tools

As a static analysis tool for js code, ESLint can work independently of webpack and other construction tools, that is, ESLint can use its command-line tool to check the specified file or file directory.

  1. Install ESLint first
npm i eslint -D
  1. Generate configuration file eslintrc.js
    In order for ESLint to take effect, you must create a configuration file, commonly called eslintrc.js. However, in most cases, we do not create it manually, but based on the commands provided by ESLint:
npx eslint --init
// perhaps
npm init @eslint/config

Execute the command to generate ESLint configuration file. At this time, ESLint will pop up multiple choices in turn, and finally generate different configuration files according to the options we selected.
Note: Although the configuration files generated based on different choices may be different, the information in these configuration files can be modified.

  1. Use the command line tool to statically check the target file
npx eslint ./src/index.js

Profile information for ESLint

module.exports = {
    "env": {
        "browser": true, // The js code to check is running on the browser side
        "commonjs": true, // Using commonjs modular specification
        "es2021": true // You can check the syntax before ES2021
    },
    "extends": [
        "eslint:recommended", // Inherit the inspection rules officially recommended by eslint
        "plugin:react/recommended", // Inherit the inspection rules recommended by react
        "plugin:@typescript-eslint/recommended" //Inherit the check rules recommended by typescript
    ],
    "parser": "@typescript-eslint/parser", // js code parser, eslint default code parser is espree; Due to the existence of ts code in the project, the compiler is designated as a parser for parsing ts code
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true  // jsx syntax is also checked
        },
        "ecmaVersion": "latest",  // Corresponding to ECMA version configured in env
		"sourceType":"module" // If we choose Commonjs as the modular specification during initialization, if we want to support ESmodule at the same time, we must write this sentence here in the parsing configuration, otherwise an error will be reported
		
    },
    "plugins": [
        "react",  
        "@typescript-eslint"
    ],
    "rules": {
    }
}

Basic principles of ESLint

  1. ESLint performs lexical analysis on the source code to be checked through the default JS compiler espree and converts it into an array of tokens
  2. The tokens array is parsed to generate an abstract syntax tree AST
  3. Access each node while traversing AST in depth, and apply plug-ins for each node
  4. When the plug-in works, it reports and fixes the syntax errors that do not comply with the rules

Several ideas to solve the error reporting of ESLint

The following is a piece of source code, which inherits the configuration rules recommended by airbnb for code inspection:

const a = "hello world"

function demo(){
	return 100
}

export {
	
}

Execute NPX ESLint/ src/ESLint/index. JS command, the console displays that ESLint has checked the following errors:

 1:7   error  'a' is assigned a value but never used            no-unused-vars
  1:11  error  Strings must use singlequote                      quotes
  1:24  error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  1:24  error  Missing semicolon                                 semi
  2:1   error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  3:16  error  Missing space before opening brace                space-before-blocks
  3:16  error  Missing space before opening brace                space-before-blocks
  3:17  error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  4:1   error  Unexpected tab character                          no-tabs
  4:1   error  Expected indentation of 2 spaces but found 1 tab  indent
  4:12  error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  4:12  error  Missing semicolon                                 semi
  5:2   error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  6:1   error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  7:9   error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  8:1   error  Unexpected tab character                          no-tabs
  8:1   error  Trailing spaces not allowed                       no-trailing-spaces
  8:2   error  Expected linebreaks to be 'LF' but found 'CRLF'   linebreak-style
  9:2   error  Newline required at end of file but not found     eol-last
  9:2   error  Missing semicolon                                 semi

Solution to ESLint error reporting idea 1: directly close the corresponding rule verification

  1. Linebreak style: this rule means to enforce a consistent line break style.
    The reason for the error is that in the windows operating system, the line feed character is usually carriage return (CR) plus line feed separator (LF), that is, carriage return and line feed (CRLF). However, in Linux and Unix, only a simple line feed separator (LF) is used. The corresponding control characters are "\ n" (LF) and "\ r\n"(CRLF). Since the rules inherited from airbnb require all line breaks to be LF, an error will be reported. Here we close it first.

  2. Space before blocks: this rule will enforce the consistency of spaces before blocks.
    This rule requires us to always have a space before the block statement. The value of never means that there will never be a space before the block, and the value of always means that there must be a space before fast. Close it first.

  3. No unused vars: variables declared but never used are not allowed. Close the rule.

  4. No tabs: tab characters are not allowed anywhere in the file, including code and comments. Close it.

There are two ways to set rules in ESLint: number and string:
"Off" or "0" means that the specification verification is turned off
"warn" represents an error level and does not exit the program
"Error" or 2 means that the rule is closed, and the program will exit if an error level error is used

rules: {
  "linebreak-style":"off",
  "space-before-blocks":"off",
  "no-unused-vars":0,
  "no-tabs":"off",
},

The second idea to solve the ESLint error: define the rules suitable for your project according to your own source code, which will overwrite the inherited rules

  1. quotes: this rule enforces consistent backtick, double quotation mark or single quotation mark. Single quotation mark is defined in airbnb. Here we customize a double quotation mark rule to override this inherited rule
rules: {
	"quotes":["error","double"],
}

Solution to ESLint error reporting idea 3: modify the source code to solve the verification error

  1. semi: this rule requires that there must be a semicolon at the end of a line of code. Here we follow its rules to modify the source code and add a semicolon at the end of the code;.
  2. Indent: this rule requires the indent of the code to be separated into two spaces. Here we follow its rules to modify the source code and change the indent of the code to two spaces
  3. EOL last: this rule requires that the last line of the file should have a blank line. Here we follow its rules to modify the source code and add a blank line at the end of the code

ESLint plug-in in VSCode

Configure eslint loader in webpack for code checking

In the actual project development, it is impossible for us to use the command line tool to check the js files of the whole project in turn. In order to better help us find code style errors in the development stage, we can also use a special eslint loader to deal with them:

  1. Install eslint loader
npm i eslint-loader -D
  1. Configure eslint loader
    Note: the writing order of eslint loader should be at the end of the array. First conduct code verification, and then use Babel loader for code conversion.
module:{
	rules:[
		{
			test:/\.js$/,
			exclude:/node_modules/,
			use:[
				"babel-loader",
				"eslint-loader"
			]
		},
		
	]
},

After configuration, the js code can be verified every time npm run build is packaged or the local service is started. The code will not be converted until it passes the verification. However, it should be noted that the verification of the code by using eslint loader works in the compilation stage of the code, not in the writing stage of the code.

Use ESLint plug-in to check the code in IDE tools such as VSCode

In fact, eslint loader will not be used in real project development for two reasons:

  1. Eslint loader starts to work in the compilation phase of the code. When we write the code, we can't help us check for errors
  2. Eslint loader will definitely affect the speed of the final package build

Therefore, the best case is that ESLint can help us detect errors when writing code, and automatically repair the detected code style class errors.

The operation principle of ESLint plug-in in VSCode is that VSCode will be read in the root directory of the project by default eslintrc.js configuration file. If there is this file, the code will be statically checked according to the configuration information in this file. If not, the code will be checked according to the default rules of VSCode, and the error report will be displayed on the terminal in real time.

Keywords: Webpack

Added by duny on Sun, 06 Mar 2022 05:50:19 +0200