Official Documentation [English version] English documents

Official Document [Chinese version] Chinese document

Original address blog address

What Eslint is for

ESLint was originally an open source project created by Nicholas C. Zakas in June 2013. Its goal is to provide a plug-in javascript code detection tool.

Why use Eslint

ESLint is an open source JavaScript code checking tool. Code review is a static analysis that is often used to find problematic patterns or code and is not dependent on specific coding styles. Most programming languages have code checks, and compilers typically have built-in checks.

However, due to the dynamic weak-typed language feature of javascript, it is easy to make mistakes in development if it is not restrained. It is precisely because of this feature that when errors occur in the program, we need to spend more time debugging during execution. Eslint was created so that developers could find bugs during development rather than during execution.

Eslint maintains its plugins, allowing developers to customize their own rules, or to follow the rules of a large community or team. All rules are pluggable, and some rules are built in for ease of use.

The installation

  • Partial installation:npm install eslint --save-dev
  • Global installation:npm install eslint -g
  • Version requirements nodeJS >= 6.14, NPM 3+

use

First we need to use ESLint we need to configure an ESLint specific configuration file to be placed in the root directory of the project, which can be generated directly using a COMMAND-LINE interface tool, /node_modules/.bin/eslint –init /node_modules/.bin/eslint –init /node_modules/.bin You can choose JS, JSON, YAML, etc., and select some rules you need. If this is your first time, I recommend that you press Enter all of them and select None for the first time. All annotated to make it easier for you to understand.

Module. exports = {"env": {// environment "browser": true, "es2021": true}, "extends": "Eslint :recommended", // a shareable configuration name, eslint:recommended or esLint :all, which means that some built-in rules are enabled by default, including, In https://eslint.bootcss.com/docs/rules/, you can view the built-in rules "parserOptions" : {" ecmaVersion ": "Latest ", // Specify the ECMAScript version "sourceType" you want to use: "Module" //"script" (default) or "module" (if your code is an ECMAScript module)}, "rules": {// Where to configure rules here are the rules we need to configure}}Copy the code

Rule configuration

Precautions for basic configuration rules
  • “Off” or 0 – Turns off the rule

  • “Warn” or 1 – Turn on the rule and use a warning level error: WARN (will not cause the program to exit)

  • “Error” or 2 – Enable the rule with error level: error (when triggered, the program will exit)

  • The normal configuration is usually key-value pairs, so this type of configuration has no attributes and you just need to turn it on and off like

    "no-cond-assign": 2,
    "no-console": 1,
    Copy the code

    Of course, some attributes have their own attributes, which need to be configured while controlling the switch, for example

    {rules: {' quotes' : [' error ', 'single'], / / if not single quotes, then an error: 'one - var' [' error '{' var' : 'always', // each function scope allows only 1 var declaration 'let': 'never', // each block scope allows multiple lets to declare 'const': 'never', // allow multiple const declarations per block scope}]}}Copy the code
  • Eslint can be configured in one of the following five formats

    • JavaScript – Use.eslintrc.js and output a configuration object.
    • YAML – Use.eslintrc.yaml or.eslintrc.yml to define the structure of the configuration
    • JSON – Using.eslintrc. JSON to define the structure of the configuration, ESLint’s JSON files allow JavaScript style comments.
    • Deprecated – Use.eslintrc, either JSON or YAML.
    • Package. json – Create an eslintConfig property in package.json and define the configuration there.
  • Multiple configurations are sorted according to the following priorities

    1 .eslintrc.js
    2 .eslintrc.yaml
    3 .eslintrc.yml
    4 .eslintrc.json
    5 .eslintrc
    6  package.json
    Copy the code
List of common configuration rules more rule parametersThe official documentation】
Configuration properties Configuration instructions The recommended configuration
comma-dangle Whether closing commas are allowed in objects [“error”, “never”]
no-cond-assign Assignment operators are not allowed in conditions of conditional statements 2
no-console Console statements are not allowed 2
no-constant-condition A condition statement does not allow constant quantities to occur in conditions 2
no-control-regex Control characters are not allowed in regular expressions 2
no-debugger Debugger statements are not allowed 2
no-dupe-args Function definitions do not allow duplicate arguments 2
no-dupe-keys Duplicate keys are not allowed in the object 2
no-duplicate-case Duplicate case tags are not allowed in switch statements 2
no-empty Empty code blocks are not allowed 2
no-empty-character-class Empty character groups are not allowed in regular expressions 2
no-ex-assign Reassigning exception variables is not allowed in a try catch statement 2
no-extra-boolean-cast Unnecessary Boolean conversions are not allowed 2
no-extra-parens Unnecessary parentheses are not allowed 0
no-extra-semi Unnecessary semicolons are not allowed 2
no-func-assign Reassignment of function declarations is not allowed 2
no-inner-declarations It is not allowed to declare functions in nested code blocks [“error”, “functions”]
no-invalid-regexp Invalid regular expressions are not allowed in the RegExp constructor 2
no-irregular-whitespace Irregular Spaces are not allowed 2
no-negated-in-lhs It is not allowed to reverse the leftmost operand in an in expression statement 2
no-obj-calls Global object properties are not allowed to be called as functions 2
no-regex-spaces Multiple consecutive Spaces are not allowed in a regular expression 2
quote-props Object whether attribute names need to be quoted 2
no-sparse-arrays No empty positions are allowed in the array 2
no-unreachable Impossible statements are not allowed after return, throw, continue, or break statements 2
use-isnan Use isNaN() when asking to check NaN 2
valid-jsdoc Enforce JSDoc comments [“error”, {“requireReturn”: false, “requireParamDescription”: false, “requireReturnDescription”: true }]
valid-typeof Enforces a valid string when comparing typeof expressions [“error”, { “requireStringLiterals”: true }]
block-scoped-var Place variable declarations in the appropriate code block 2
complexity Limit the complexity of conditional statements 0
consistent-return Enforces the return statement to return a value with or without a value 2
curly Enforces the curly brace style [“error”, “all”]
default-case A default statement is required in the switch statement 0
dot-notation Use a dot to get object attributes [“error”, {“allowKeywords”: false, “allowPattern”: “”}]
eqeqeq We use strict equals when we compare [“error”, “smart”]
no-alert Alert, confirm, prompt statements are not allowed 1
no-caller Arguments. callee and arguments.caller attributes are not allowed 2
guard-for-in Monitor the for in loop for unexpected situations 0
no-div-regex Regular expressions that look like division cannot be used 2
no-else-return If the if statement has a return, the return in else does not have to be in else 0
no-labels Label statements are not allowed [“error”, { “allowLoop”: false “allowSwitch”: false }]
no-eq-null Null is not allowed with == or! = 2
no-eval Eval () is not allowed 2
no-extend-native Extension of native objects is not allowed 2
no-extra-bind Unnecessary function bindings are not allowed 2
no-fallthrough The Switch is not allowed to execute all cases sequentially 2
no-floating-decimal Floating point numbers are not allowed to miss digits 2
no-implied-eval Implicit eval() is not allowed 2
no-iterator The __iterator__ attribute is not allowed 2
no-lone-blocks Unnecessary nesting of code blocks is not allowed 2
no-loop-func Function declarations are not allowed in loop statements 2
no-multi-spaces No extra Spaces are allowed 2
no-multi-str It is not allowed to wrap a string with \ 2
no-global-assign Redistribution of native objects is not allowed 2
no-new It is not allowed to new an instance without assigning or comparing 2
no-new-func New Function is not allowed 2
no-new-wrappers New String, Number, and Boolean objects are not allowed 2
no-octal Octal literals are not allowed 2
no-octal-escape Octal escape sequences are not allowed 2
no-param-reassign Reassignment of function parameters is not allowed 0
no-redeclare Variables are not allowed to be declared twice 2
no-return-assign Assignment statements are not allowed in return statements 2
no-script-url Javascript is not allowed :void(0) 2
no-self-compare Don’t allow yourself to be compared to yourself 2
no-sequences Comma expressions are not allowed 2
no-throw-literal Throw “error” is not allowed 2
no-unused-expressions Useless expressions are not allowed 2
no-void The void operator is not allowed 2
no-warning-comments Warning remarks are not allowed [1, {“terms”: [“todo”, “fixme”, “any other term”]}]
no-with The with statement is not allowed 2
radix Using parseInt enforces a base to specify whether it is decimal or some other base 1
vars-on-top Var must be placed at the top of the scope 0
wrap-iife Execute the parenthesis style of the expression immediately [2, “any”]
yoda Yoda conditions are not allowed in if conditions [2, “never”, {“exceptRange”: true}]
strict Use strict mode [2, “function”]
no-catch-shadow Try catch statements are not allowed to accept err variables that have the same name as external variables 2
no-label-var Tags and variables are not allowed to have the same name 2
no-shadow A variable in an external scope cannot have the same name as a variable or parameter in the scope it contains 2
no-shadow-restricted-names The js keyword and reserved word cannot be used as function or variable names 2
no-undef Undeclared variables are not allowed 2
no-undef-init It is not allowed to assign undefined to a variable when initializing it 2
no-undefined Undefined is not allowed as an identifier 2
no-unused-vars Variables or parameters that are not used after being declared are not allowed [2, {“vars”: “all”, “args”: “after-used”}]
no-use-before-define It is not allowed to use variables before they are defined [2, “nofunc”]
brace-style Curly brace style [2, “1tbs”, { “allowSingleLine”: false}]
camelcase Enforce hump naming rules [2, {“properties”: “never”}]
comma-style The comma style [2, “last”]
consistent-this When getting the current environment this is used in the same style [0, “self”]
eol-last The file ends with a newline character 2
func-names Function expressions must have names 0
func-style Function style, which specifies that only function declarations or function expressions can be used 0
key-spacing The Spaces before and after the colon in an object literal [2, {“beforeColon”: false, “afterColon”: true}]
max-nested-callbacks Callback nesting depth 0
new-cap Constructor names must be capitalized [2, {“newIsCap”: true, “capIsNew”: false}]
new-parens The constructor must have braces when new 2
newline-after-var Variable declarations must be followed by a blank line 0
no-array-constructor Array constructors are not allowed 2
no-inline-comments Inline comments are not allowed 0
no-lonely-if Else statements are not allowed to contain only if statements 0
no-mixed-spaces-and-tabs It is not allowed to mix tabs and Spaces [2, “smart-tabs”]
no-multiple-empty-lines No more than two blank lines [2, {“max”: 2}]
no-nested-ternary Nested ternary operators are not allowed 2
no-new-object Disallow new Object() 2
fun-call-spacing When a function is called, there must be no space between the function name and () 2
no-ternary Ternary operators are not allowed 0
no-trailing-spaces No Spaces are allowed at the end of a line 2
no-underscore-dangle Identifiers are not allowed to start with an underscore 2
no-extra-parens Redundant parentheses are not allowed 0
one-var Enforce variable declarations together 0
operator-assignment The style of the assignment operator 0
padded-blocks Whether the first and last lines of a block are empty [2, “never”]
quote-props Attribute names in quotation marks in object literals 0
quotes Quote style [1, “single”, “avoid-escape”]
semi Enforces a semicolon ending of a statement [2, “always”]
semi-spacing Space before and after [2, {“before”: false, “after”: true}]
sort-vars Sort when declaring variables 0
space-before-blocks The space before the block [2, “always”]
space-before-function-paren Space before parentheses when a function is defined [2, {“anonymous”: “always”, “named”: “never”}]
space-infix-ops Spaces around the operator [2, {“int32Hint”: true}]
keyword-spacing Spaces before and after the keyword 2
space-unary-ops Unary operators are not preceded by Spaces [2, { “words”: true, “nonwords”: false}]
wrap-regex Regular expression literals are enclosed in parentheses 2
no-var Use let and const instead of var 0
generator-star-spacing Spaces before and after generator functions [2, “both”]
max-depth Nested block depth 0
max-len Maximum length of a line, in characters 0
max-params How many arguments can a function take 0
max-statements There are at most a few declarations inside a function 0
no-bitwise Bitwise operators are not allowed 0
no-plusplus The ++ — operator is not allowed 0
indent Enforces a consistent indentation style 2
no-delete-var The delete operator is not allowed 2
no-proto The __proto__ attribute is not allowed 2

ESLint provides a large number of built-in Rules. Here is a list of ESLint Rules, but you can also add more Rules via plug-ins.

It is recommended that teams standardize open source configurations

The above is some basic configuration, the specific use of it can be configured by themselves, the general configuration of this kind of rules can refer to the more popular specifications on the market, the use of other people’s specifications plus their own configuration. The most popular open source configuration currently on the market is the one used most by the Airbnb team. The following configurations are recommended:

  • In no case does esLint mention that all checked rules are built in rules
  • Eslint :all: All rules built into ESLint;
  • Eslint-config-standard: the JS specification for standard;
  • Eslint-config-prettier: Shuts off a rule that conflicts with ESLint and other extensions;
  • Eslint-config-airbnb-base: JS specification for AirBab;
  • Eslint-config-alloy: the product of Tencent AlloyTeam, you can configure the stack of your project very well, such as React, Vue (Vue 3.0 support), TypeScript, etc.
How to use

To use someone else’s configuration, you usually just download the corresponding dependency and add it to the extends inheritance, which can be either a string or an array.

{ extends: ['eslint:recommended', // is an official extension of ESLint with built-in recommended rule 'plugin:vue/essential', // is a plugin type extension 'eslint-config-standard', "@vue/prettier", "@vue/prettier", "@vue/prettier", "@vue/prettier", "@vue/prettier", "@vue/prettier" './node_modules/coding-standard/.eslintrc-es6' // a path to execute configuration files]}Copy the code

How to use plug-in plugins

ESlint plugins do what:

The first thing you need to know is that Eslint is essentially a code detection tool. By default, Eslint can only detect JS files, which is not possible if you need to engineer files that are compatible with other syntax such as [.vue], [.jsx], etc. So we need to add some plug-ins to realize the detection of files in non-JS format.

How to configure plugin

Eslint-related plugins come in two command names, namespace and band, for example

  • Eslint-plugin-xxx Anything that starts with eslint-plugin- can be omitted from the extends inheritance rule like the one above and only XXX is required
  • The @ sign indicates that the namespace should be imported normally
{ plugins: ['jquery',// refers to eslint-plugin-jquery '@jquery/jquery', // refers to @jquery/eslint-plugin-jquery '@foobar', Foobar /eslint-plugin]}Copy the code

When you need to configure extends and Rules based on plug-ins, you need to add a reference to the plug-in, such as:

{
    plugins: [
        'jquery',   // eslint-plugin-jquery
        '@foo/foo', // @foo/eslint-plugin-foo
        '@bar,      // @bar/eslint-plugin
    ],
    extends: [
        'plugin:jquery/recommended',
        'plugin:@foo/foo/recommended',
        'plugin:@bar/recommended'
    ],
    rules: {
        'jquery/a-rule': 'error',
        '@foo/foo/some-rule': 'error',
        '@bar/another-rule': 'error'
    },
}
Copy the code

The above configuration comes from ESLint plugins

Popular open source specification recommendations

How do I know which rules can be configured for an extension and the specific restrictions for each rule? Here’s a quick link to a list of well-known and widely used rules in the industry:

  • ESLint :recommenmed ESLint :recommenmed ESLint: Recommenmed
  • Prettier rules
  • standard rules
  • airbnb rules
  • AlloyTeam vue rules

Priority of the rule

  • If the extends configuration is an array, it will eventually merge all rule items, and in case of a conflict, the latter overwrites the former.
  • Rules configured separately through rules have a higher priority than extends;
Other configuration

Set the current directory to root

ESLint checks configuration files for the following steps:

    1. Look for.eslintrc.* and package.json in the same directory as the file you want to test.
    1. Then look in the parent directory until you reach the root directory of the file system.
    1. If you found root: true configuration in the previous two steps, stop looking for.eslintrc in the parent directory;
    1. If no, go back to the default configuration in the user home directory ~/.eslintrc.

It is common practice to put the ESLint configuration files in the root directory of the project, so to avoid looking up configuration files in the parent directory for ESLint validation, add root: true to the configuration files.

{
    root: true,
}
Copy the code

For details, see the eslintrc configuration file

How to configure

ESLint supports three configurations:

  • Command line: not recommended, not introduced;
  • Notes in single file: not recommended, not introduced;
  • Configuration file: The configuration file can be of several types, such as.js,. Yml, and json. It is recommended to use.eslintrc.js, which can also be configured in thepackage.jsonIn the middle.
  1. Install NPM I ESlint -d

  2. /node_modules/.bin/eslint –init or NPX eslint –init both work the same way, generating.eslintrc.js in the root directory

  3. You can configure a set of rules for yourself from the above introduction, so how do we trigger?

    1. Verifying a single file

      npx eslint a.js b.js
      Copy the code
    2. Verifying a directory

      npx eslint src
      Copy the code
    3. It’s not enough to just configure a vue-eslint-parser, so Eslint needs to find.vue files when it looks for files. You can specify the file format to verify with –ext

      npx eslint --ext .js,.jsx,.vue src  
      Copy the code
    4. Rules with flags in the list of all rules can be fixed automatically by Eslint, so how do we fix this automatically? All you need to do is name it –fix, which is similar to the command to verify the file, but you just need to add the fix command

      npx eslint --fix src
      Copy the code
    5. Of course, it is not easy to remember every time we input it ourselves in the project. We can configure detection and repair commands in package.json:

      {
          "scripts": {
              "lint": "npx eslint --ext .js,.jsx,.vue src",
              "lint:fix": "npx eslint --fix --ext .js,.jsx,.vue src",
          }
      }
      Copy the code
    6. Filter I don’t need to detect file, in some cases we do not need to detect some files, or for some reason don’t want to test a file under the current scenario, we only need to create in the project root directory. Eslintignore file, in which the specified directory or file, the path in the root directory to the path of the relative address. Also, Eslint ignores /node_modules/ files by default, and this directory does not need to be configured.

Cold knowledge

  1. SourceType has two values, script and module. Module is required for ES6+ syntax and syntax with import/export.
  2. Eslint –init can select Airbnb, Standard, recommended standard only if “To check syntax, find problems, and Enforce code style” is selected.
  3. Env and Node: true are compatible with each other. If env is configured with browser: true, node: true can be compatible with global variables that are compatible with different environments, such as global, process, etc.
  4. Rule strength is Airbnb > Standard > recommended
  5. Normally, you don’t fix a file, you configure commands on the project to fix the whole world at once
  6. Cooperate withPrittierCan work better
  7. Cooperate withVscodeTo achieve automatic saving, you need to download it firstEslint plug-in, preferences -> Settings -> Search for “autofix”. Auto Fix On Save. You can fix it automatically when you save it.

conclusion

  • What does ESLint do, how is it generated, used, and configured
  • How to configure rules, what common rules are there, and how to trigger them
  • How to use other people’s open source rules, how to inherit, how to modify inherited rules
  • How to use plug-ins, what do they do, and how do they work together
  • How to detect and autorepair files and configure detect and repair commands
  • How to detect non-JS files

That’s all we need to know to get started, but later we’ll look at how to introduce Eslint in Vue and React projects and how to use integration