• 1. What is EsLint
  • 2. Why use ESLint
  • 3. Get started
  • 4. Use ESLint to check code
    • 4.1. On the command line
    • 4.2. Used in VSCode
  • 5. ESLint configuration
    • 5.1. Configuration of the locale
      • 5.1.1. Environmentalenv
      • 5.1.2. Global variablesglobals
      • 5.1.3. Parsing optionsparserOptions
      • 5.1.4. Use other parsersparser
    • 5.2. Rule Configurationrules
    • 5.3. Use plug-insplugins
      • 5.3.1. Naming of plug-ins
      • 5.3.2. What can plug-ins bring
    • 5.4. Inheritance configurationextends
    • 5.5. Match the application configuration using Globoverrides
    • 5.6. Ignore filesignorePatterns
    • 5.7. Use comments for configuration
    • 5.8. Merge layers and rules
      • 5.8.1. Configuration file hierarchy
      • 5.8.2. Configured priorities
      • 5.8.3. Rule coverage
  • 6. Other resources

1. What is EsLint

Lint (Linter) is a static code analysis tool used to flag coding errors, style problems, and unstructured (bug-prone) code in code. Simple to understand is a code inspector, check whether the object code complies with the syntax and prescribed style habits. ESLint is based on the ECMAScript/JavaScript syntax and can:

  • Check for JavaScript code syntax problems.
  • Flags code that does not conform to the specification based on configured rules.
  • Automatically fixes some structure and style issues.

ESLint is flexible and highly customizable, allowing users to configure rules and other configurations to be applied in a project in a variety of ways, customize their own rules, and extend functionality through plug-ins.

2. Why use ESLint

Using ESLint in a project can be extremely helpful both individually and as a team.

  • For the individual:
    • Avoid syntax bugs and structural problems in your code.
    • Format code, automatically beautify the code.
  • To the team:
    • Unify the code styles of different people in the team and project to reduce maintenance costs.
    • (teams that already have established code specifications) constrain team members to use a common specification.

Today, most engineering projects use ESLint to help examine and unify the code in the project, even if there is no unified specification within the team.

3. Get started

Prerequisite: Node.js(>=12.0.0) and package.json file exists in the project directory.

  1. Installation (global installation is not recommended)
npm install --save-install eslint
Copy the code
  1. Initialize the
npx eslint --init

#Note: NPX means to find the command from the current path, that is./node_modules/.bin/eslint --init
Copy the code

ESLint will ask you a series of questions and generate the corresponding.eslintrc.* configuration file based on your answers.

/* $NPX eslint --init ➤ How would you like to use eslint? · Style ➤ What type of modules does your project use? · EsM ➤ Which framework does your project use? Re-configure your project use TypeScript? · No/Yes ✔ Where does your code run? · Browser ➤ How would you like to define a style for your project? ➤ Guide ➤ Which style guide do you want to follow? · Standard ➤ What format do you want your config file to be in? JSON * /

// The above answers correspond to the.eslint.json file below

{
  "env": {
    "browser": true."es2021": true
  },
  "extends": ["plugin:react/recommended"."standard"]."parser": "@typescript-eslint/parser"."parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12."sourceType": "module"
  },
  "plugins": ["react"."@typescript-eslint"]."rules": {}}Copy the code
  1. Configure your rules (see configuration section below)
  2. At this point, you can use ESlint to check and fix problems in your code

(Configuration part is more content, and easy to use without too much in-depth configuration, the use of ESLint will be described later, and then summarize the configuration content)

4. Use ESLint to check code

4.1. On the command line

Note: EsLint is rarely used on the command line anymore. It is usually used in conjunction with the editor via an editor plug-in to enable real-time checking during editing. This way we can get a little bit more understanding.

  • Check and print the problems found:npx eslint [file|dir|glob]*, in:
#Checking multiple files
npx eslint file1.js file2.js

#Use glob re to check all files in the directory
npx eslint lib/**
Copy the code
  • use--fixOption autofix fixes problems, such as:
#Auto-fixable problems in index.js are fixed and ignored
npx eslint --fix index.js
Copy the code

For more commands and parameters, see ESLint Docs: Command Line Interface, which I won’t go into here.

4.2. Used in VSCode

Note: in addition to VSCode, other editors also have corresponding ESlint integration methods, see ESlint Docs: Integrations.

First, install the VSCode ESlint plugin. Note that the plugin does not have built-in ESLint core code. Instead, it automatically looks for the ESLint library in the project, calls lint commands every time the user types, and flags code problems in the editor, as described in the documentation:

The extension uses the ESLint library installed in the opened workspace folder. If the folder doesn’t provide one the extension looks for a global install version.

The advantage of this is that the editor is compatible with different versions of ESLint on different projects and ensures that team members on the same project have the same VERSION of ESLint.

If you want autofix to fix the problem every time you hold it, you can set save-time fix in VSCode:

/*
* VSCode Settings JSON File
*/
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true}},Copy the code

5. ESLint configuration

Configuration files are the primary way ESLint is configured. ESLint configuration files support multiple formats, in the same directory, ESLint presses.eslintrc.js,.eslintrc.cjs,.eslintrc.yaml,.eslintrc.yml,.eslintrc.json, Json. Only one configuration file in the same directory will take effect. Among them, the commonly used is eslintrc js | json format, using eslint below. The json format.

ESLint also supports more flexible and fine-grained configuration of specific files, local code using comments, often used to replicate rules for particular code snippets.

ESLint configuration includes the execution environment env, global variable globals, and rules.

5.1. Configuration of the locale

As we know, different execution environments inject different global variables into JavaScript, such as window in the browser, and Process in Node.js. In addition, different versions of the ECMAScript syntax support different syntax and features. Therefore, the legitimacy of the code is dependent on the execution environment and the VERSION of ES supported by the environment.

In order for ESLint to correctly identify legitimate code, we must configure the execution environment and supported syntax options for the code.

5.1.1. Environmentalenv

ESLint does not enable any environment by default. You can use “env_name”:true under env. Environments are not mutually exclusive and multiple environments can be enabled at the same time, for example:

{
  "env": {
    "browser": true."node":true."es6":true}}Copy the code

When the environment is enabled, ESLint can normally parse global variables in code, possibly with the corresponding parsing options enabled. Common environments are:

  • browser: browser global variable.
  • nodeNode.js global variables and scopes.
  • es6: Supports ES6 syntax (excluding ES Module) and enables ES6 syntax parsing options.

For a complete list of Environments, see ESLint Docs: Specifying Environments.

5.1.2. Global variablesglobals

Env can easily support global variables in specific environments, but JavaScript execution environments are much more complex, and each module and external dependency has the potential to inject its own global variables. To avoid this being identified as an error, you need to indicate the external global variables used in your code in your configuration. Globals field is used to set the global variable in your code, syntax for {” var_name “:” off “|” readonly “|” writable “}, such as:

{
  "globals": {"$":"readonly"."globalState":"writable"}}Copy the code

“Off” is used to turn off global variables brought by env. For example, in browsers that support most ES2015 syntax, but don’t support Promises, you can set:

{
  "env": {"es6": true
  },
  "globals": {"Promise":"off"}}Copy the code

5.1.3. Parsing optionsparserOptions

ESLint provides support for language features such as ES syntax and JSX when parsing. ESLint supports ES5 syntax by default.

Configuration syntax The syntax is as follows:

{
  "parserOptions": {/* ecmaVersion: specifies the ECMA syntax version. Value: * - "latest": Using the latest version, now (2021) equals 12 * - Version number: 3, 5(default), 6, 7, 8, 9, 10, 11, 12 * - Year nomenclature: 2015(=6), 2016(=7), 2017(8)... * / 
    "ecmaVersion":  "latest"./ * sourceType: type of script, regular script, or script * ES module values: "script" (the default) | "module" (ES module script) * /
    "sourceType":"module"./* ecmaFeatures: supported feature syntax */
    "ecmaFeatures": {
      
      // Support using return globally
      "globalReturn": true.// Strict mode is used by default (ES 5 or above)
      "impliedStrict": true.// Support JSX syntax
      "jsx": true}}}Copy the code

Note that turning on the higher ES resolution option does not automatically support the corresponding ES global variable. So, to support the latest ES syntax:

{
  "env": {Support es syntax global variable recognition, which is a must
    "es2021": true,},/* The following is optional because ES2021 automatically sets "ecmaVersion": 12 "parserOptions": {"ecmaVersion": 12} */
}
Copy the code

5.1.4. Use other parsersparser

ESLint uses the Espree parser by default. You can also use other parsers through the Parser field. The parser needs to satisfy two conditions:

  • It must be a Node module and can be found in the configuration file directory. For example, the NPM package in the same directory, a js file specified by path.
  • Satisfies the ESLint parser interface.

If you use language enhancement tools (TypeScript, Babel) or frameworks (React, Vue) in your project, you need to use the corresponding parser. In TypeScript’s case, to parse code correctly, you need:

  1. in.eslintrc.jsonInstall the parser in the corresponding directory
npm install --save-dev @typescript-eslint/parser
Copy the code
  1. In the configuration file
{
  "parser": "@typescript-eslint/parser"
}
Copy the code

Note: When using other plug-ins, parserOptions is still valid and is passed to the parser as a parameter.

5.2. Rule Configurationrules

Rules is the most important configuration in ESLint, specifying which rules will be used to constrain code.

ESLint provides a number of built-in rules. In addition, plug-ins can be used to add rule sets that are appropriate for a particular scenario.

Rules of configuration syntax is {” rules “: {” rule_name” : the state | [the state, the options of…]}}, among them, the state on behalf of the enumeration values:

  • "off"or0: Close rule, often used to close a sourceextendsRules in.
  • "warn"or1: Warning is generated when the rule verification fails.
  • "error"or2: If the rule verification fails, an error message is emitted, and 1 is returned, indicating that the lint check fails.

The following configurations are valid:

{
  "rules": {// Use "off", "warn", "error"
    "no-console": "warn".// Use numbers (not recommended)
    "for-direction": 1.// Array syntax, but no additional configuration items
    "no-else-return": ["error"].// Array syntax, a configuration item
    "eqeqeq": ["error"."always"].// Array syntax, multiple configuration items
    "quotes": ["error"."double", { "avoidEscape": true}}}]Copy the code

5.3. Use plug-insplugins

ESLint supports third-party plugins. Before using ESLint, install the NPM package in the directory of the configuration file.

After installing the plugins, you can add the plugins needed by the configuration file to ESLint’s plugins array. However, plugins are disabled by default, so plugins are only a prerequisite for using plugins. You must enable rules in rules,extends, and Env.

{
  "plugins": ["jest"]."extends": ["plugin:jest/recommended"]."env": {"jest/global":true
  },
  
  "rules": {"jest/valid-expect": "error"}}Copy the code

5.3.1. Naming of plug-ins

ESLint specifies the naming of plugins:

  • eslint-plugin-<plugin-name>abbreviations<plugin-name>, such as:eslint-plugin-jqueryabbreviationsjquery.
  • @<scope>/eslint-plugin-<plugin-name>abbreviations@<scope>/<plugin-name>, such as:@jquery/eslint-plugin-jqueryabbreviations@jquery/jquery.
  • @<scope>/eslint-pluginabbreviations@<scope>, such as:@jquery/eslint-pluginabbreviations@jquery.

The shorthand without the ESlint-plugin is generally used.

5.3.2. What can plug-ins bring

ESLint specifies rules or other configurations within plug-ins using /XXX. According to ESLint Docs: Working with Plugins, a plugin can bring:

  • Additional rules such as{"rules": {"react/boolean-prop-naming": "warning"}}.
  • Environment, such as{"env": {"jest/global": true}}.
  • The configuration, such as{"extends": ["plugin:react/recommended"]}.
  • Preprocessor, e.g{"process": "a-plugin/a-processor"}.

5.4. Inheritance configurationextends

Extends makes it easy to inherit all the features of an existing configuration, including rules, env, extends, and so on.

Configuration inheritance is similar to “inheritance of classes” in object orientation. If the inherited configuration is the parent configuration and the inherited configuration is the child configuration, the child configuration has all the features of the parent configuration, and the rules in the child configuration overwrite the same rules in the parent configuration. Configuration inheritance is also transitive.

Configuration inheritance greatly facilitates the sharing of common configurations between projects and avoids the tedious configuration of a large number of rules each time.

The extends array contains all the parent configurations inherited from the configuration. {“extend”: “config-name”} can also be used when there is only one parent configuration.

The parent configuration can be specified in several ways:

  • ESLint has built-in configuration"eslint:recommended""eslint:all".
  • Package name of the shared configuration"eslint-config-<config-name>", and its abbreviations are similar to plug-in names. Such as
{
  "extends": ["standard"] / / with eslint - config - standard
}
Copy the code
  • Configuration exported within the plug-in"plugin:a-plugin/config".plugin:The prefix is used to distinguish the shorthand configuration from the plug-in package name. Such as
{
  // Don't forget plugins
  "plugins": ["react"]."extends": ["plugin:react/recommended"]}Copy the code
  • ESLint Specifies the file path configured. Such as{"extends": "./.my-eslintrc.json"}.

5.5. Match the application configuration using Globoverrides

Overrides support matching specific file sets by Glob pattern, and additional application of different configurations. For example, we often need to apply different rules in a project depending on the file type.

Overrides is an array of configuration objects that support most ESLint configurations, plus an array of files and excludedFiles for matching files. When files are lint checked, the relative path of the object file relative to the configuration file matches the two sets of Glob patterns, and if the path satisfies either of the files and does not satisfy either of the excludedFiles patterns, the configuration will be applied.

/*./ SRC apply the no-alert rule */ except for js files under a.js
{
  "overrides": [{"files": ["src/*.js"]."excludedFiles": "a.js"."rules": {
        "no-alert": "warn"}}}]Copy the code

5.6. Ignore filesignorePatterns

The ignorePatterns array contains a set of glob patterns that are ignored when a file path matches any of them, acting like.gitignore.

Lint checking for packaged products is generally not desirable:

{
  "ignorePatterns": ["**/dist/**"."**/output/**"]}Copy the code

5.7. Use comments for configuration

In addition to file configuration, ESLint also supports the use of comments for in-file configuration, which is more flexible and often used as a supplement.

Note: If executed through the command line, the configuration can also be injected through command parameters, which is not discussed here.

ESLint comments distinguish between // and /**/, and can state the cause at the same time. The cause is placed after configuration content, separated by two or more -.

Common comments:

  • Most of the time, you just want to slack off and turn off annoying rules:
/* * single line close */
alert('foo'); // eslint-disable-line

// eslint-disable-next-line -- I don't want eslint 
alert('foo');

/* eslint-disable-next-line */
alert('foo');

alert('foo'); /* eslint-disable-line */

// eslint-disable-next-line no-alert, quotes, semi
alert('foo');

foo(); // eslint-disable-line plugin/rule-name

/* * block closed */
/* eslint-disable */
console.log("bar")
alert('foo');
/* eslint-enable */

/* eslint-disable no-alert, no-console */
alert('foo');
console.log('bar');
/* eslint-enable no-alert, no-console */

/* * Close the entire file, using eslint-disable */ on the first line
/* eslint-disable */
alert('foo');
/ /...

/* eslint-disable no-alert */
alert('foo');
/ /...
Copy the code
  • You can directly configure rules:
/* ESlint quotes: ["error", "double"], curly: 2 ----- String contents containing '', do not want to use the transfer and template string */
const foo="'bar'"
Copy the code
  • Global variables:
// var1 is read-only, var2 is read and write
/* global var1, var2: writable */
Copy the code
  • Environment:
/* eslint-env node, mocha */
Copy the code

5.8. Merge layers and rules

5.8.1. Configuration file hierarchy

Although only one configuration file will take effect in a directory, ESLint supports placing multiple configuration files at different directory levels. When you execute the file Lint, you start in the directory of the current file and work your way up the configuration file hierarchy until you reach the root directory or encounter configuration {“root”: true} and merge configurations from different levels.

Note: {“root”: true} should be set in the project root directory to avoid unnecessary lookups and impacts.

5.8.2. Configured priorities

Because ESLint supports multiple configurations, configurations may conflict and precedence needs to be specified:

  • For configuration types: Comment > Command Line Parameters > Configuration File
  • At the file level: near > far
  • In the same directory: js > CJS > yaml > yML > json > package.json
  • In the same configuration:overrides > rule > extends
  • In the same choice: latter > former

5.8.3. Rule coverage

When the same rule appears in multiple rules configurations,

  • If no option is configured for this rule (only error levels are supported), the highest priority is simply applied.

  • If the rule supports additional configuration options and the higher-priority rule configuration does not provide options, the lower-priority option is inherited. Otherwise, only high-priority configurations and options are applied. Such as:

    • "eqeqeq": ["error", "allow-null"] + "eqeqeq": "warn"(High priority) ="eqeqeq": ["warn", "allow-null"]
    • "quotes": ["error", "single", "avoid-escape"] + "quotes": ["error", "single"](High priority) ="quotes": ["error", "single"]

6. Other resources

  • ESLint official website VS ESLint Chinese
  • Awesome ESLint