What is ESlint and what features does it have

Description:

ESLint is an integrated code review and repair tool. Its core function is to configure rules to limit the validity and style of code

Features:

1. Find problems: ESLint statically analyzes code to quickly find problems. ESLint is built into most text editors, and you can run ESLint as part of a continuous integration pipeline

2. Automatic fixes: Many problems found by ESLint can be fixed automatically. ESLint fixes are syntax-aware, so you don’t encounter the errors introduced by traditional find and replace algorithms

3. Customization: Preprocess code, use custom parsers, and write your own rules to use with ESLint’s built-in rules. You can customize ESLint to work exactly the way your project wants it to

ESlint use and configuration

Basic use:

The installation

npm install eslint --save-dev
Copy the code

To initialize the configuration file, the root directory is generated. Eslintrc.js

npx eslint --init
Copy the code

There are two configuration modes:

  • Configuration comments: Use JavaScript comments to embed configuration information directly into a code source file
  • Configuration files: 1. Use JavaScript, JSON, or YAML files to specify configuration information for the entire directory (handling your home directory) and its subdirectories. A stand-alone can be configured.eslintrc.*File, or directly in thepackage.jsonIn the fileeslintConfigFields specify configurations that ESLint will look up and automatically read, and you can use theThe command lineThe runtime specifies an arbitrary configuration file.

Specific configuration fields:

1. Parser and parsed parameters

The parser converts the source code into a data format called an Abstract syntax tree (AST), which the plug-in then uses to create assertions called Lint rules around the look or behavior of the code.

ESLint comes with a built-in parser (called ESpree), so if you’re only writing standard JavaScript, you don’t need a custom parser

If we want to support non-standard JavaScript syntax, all we need to do is provide an alternative parser for ESLint to use. According to the actual situation of the project, the parser is set, such as the project based on vUE framework needs to be able to parse VUE grammar parser; For projects that use TypeScript, you need to configure parsers that can parse TypeScript

This can be compared to Webpack, which can only process JS and JSON files. CSS, HTML and other files need to be understood by custom loader

Common parsers:

  • @babel/eslint-parser: A wrapper around the Babel parser to make it compatible with ESLint
  • @typescript-eslint/parser:TSLintWhen deprecated, convert TypeScript to estREE compatible form for use in ESLint

ParserOption:

{ 
    // The parser, espree by default
    parser: "espree", 
    parserOption: { 
        The default is 5. You can use 6, 7, 8, 9, or 10 to specify the ECMAScript version you want to use. You can also specify 2015 (same as 6), 2016 (same as 7), or 2017 (same as 8), 2018 (same as 9), or 2019 (same as 10) using the version number named after the year.
        ecmaVersion: 5.// Set to "script" (default) or "module" (if your code is an ECMAScript module)
        sourceType: "module".// This is an object that represents additional language features you want to use. All options default to false
        ecmafeatures: { 
            // Whether the return statement is allowed in the global scope
            globalReturn: false.// Enable global strict mode (strict mode)
            impliedStrict: false.Support JSX syntax is not the same as support React. React applies specific semantics to JSX syntax that ESLint does not recognize. If you are using the React and semantic support to React, we suggest you use [eslint plugin - React] (https://github.com/yannickcr/eslint-plugin-react).
            jsx: false./ / whether to enable support for experimental objectRest/spreadProperties
            experimentalObjectRestSpread: false}}},Copy the code
2. The env environment

An environment defines a predefined set of global variables

Specifying different environments can provide default global variables for the corresponding environment. For example, in the Browser environment, the window global variable can be used. In the Node environment, you can use the Process global variable and so on.

Available environments include: Optional configuration items are as follows:

  • browser– Global variables in the browser environment.
  • node– node.js global variables and node.js scope.
  • commonjs– CommonJS global variables and CommonJS scopes (for Browserify/WebPack packaged browser-only code).
  • shared-node-browser– Node.js and Browser are universal global variables.
  • es6– Enable all ECMAScript 6 features except modules (this option is set automaticallyecmaVersionThe parser option is 6).
  • More on official website

These environments are not mutually exclusive, so more than one can be defined simultaneously. You can specify the environment in a source file, in a configuration file, or using the –env option on the command line.

3. Globals

Additional global variables accessed by the script during execution

The no-undef rule warns when accessing variables that are not defined in the current source file. If you want to use global variables in a source file, define those global variables in Globals so that ESLint will not issue warnings

"globals": {
        "var1": "writable".// "off" disables global variables
        "var2": "readonly"
    }
Copy the code
4. The rules in the rules

The enabled rules and their respective error levels, profiles

ESLint comes with a large number of rules, and to change a rule setting you must set the rule ID to one of the following values:

  • "off" 或 0– Close rule
  • "warn" 或 1– Enable rules with warning level errors:warn(Does not cause the program to exit)
  • "error" 或 2– Enable rules, use error level errors:error(When triggered, the program exits)
"rules": {
        "eqeqeq": "off".// Use '===' and '! = = `
        "curly": "error".// Force all control statements to use the same parenthesis style
        "quotes": ["error"."double"] / / quotes
    }
Copy the code
5. Extends Extends configuration

When configuring rules in the actual project, it is impossible for the team to discuss the configuration one by one, because it takes too much energy. The usual approach is to use the industry’s common use, follow the code specification; These specifications are then introduced through extends. Extends configuration accepts strings or arrays:

  • The string specifying the configuration (of the configuration fileThe path, name of shareable configuration,eslint:recommended 或 eslint:all)
  • Array of strings: Each configuration inherits its previous configuration

Extends can be thought of as a quick configuration field for rules. The extends extends is generally configured as an industry standard first, with arrays overwriting the previous ones, and custom configuration rules overwriting rules that do not meet your desired specification

{
    "extends": [
        "eslint:recommended"."plugin:vue/essential".Eslint-config-vue /essential [plugin name: config name]
        "airbnb-base".// The actual NPM package plugin eslint-config-vue/airbnb-base
        "@vue/prettier"."./node_modules/coding-standard/.eslintrc-es6"]}Copy the code

From the above configuration, you can see that extends supports one of the following configuration types

  • eslintBeginning: is an official extension of ESLint; Common configurationeslint:recommended,eslint:all
  • pluginBeginning: is a plug-in type extension that can omit the prefix of the package nameeslint-plugin-, such asplugin:vue/essentialIn fact, it useseslint-config-vueThe plug-in, andessentialIs the configuration name, visibleThe plug-in configurationThe configuration parameters are defined in the package eslint-config-vue, as shown belowessential

  • eslint-configBeginning: fromnpmPackage, which can be used without the prefixeslint-config-For example, let’s write the aboveairbnb-base;
  • @Beginning: extension andeslint-configSame, but innpmA layer of scope is added to the packagescope;
  • A relative or absolute path to execute the configuration file;

Common extends configuration:

  • eslint:recommended: ESLint built-in recommendation rules, properties that enable a set of core rules that report common problems inThe rules pageIs labeled ✅
  • eslint:all: all rules built into ESLint;
  • eslint-config-airbnb-base: JS specification of Airbnb;
  • eslint-config-standard: JS specification of standard;
6. Plugins plugins

ESLint can define a lot of rules and introduce more rules through extends, but ultimately it just checks JS syntax. If you need to check template in Vue or JSX in React, there’s nothing you can do. So plugins were introduced to enhance ESLint’s checking capabilities and scope.

When configuring plug-ins in a configuration file, you can use the plugins keyword to store a list of plug-in names. The eslint-plugin- prefix can be omitted from the plugin name.

{
    "plugins": [
        "vue".// equivalent to "eslint-plugin-vue"
        "@typescript-eslint" // Equivalent to @typescript-eslint/eslint-plugin]}Copy the code
7. Perform other configurations

Set the current directory to root

ESLint checks configuration files for the following steps:

  1. Look in the same directory as the file you want to detect.eslintrc.*package.json;
  2. Then look in the parent directory until you reach the root directory of the file system.
  3. If you find it in the first two stepsRoot: true,Stop looking in the parent directory.eslintrc;
  4. If none is found, go back to the user home directory~/.eslintrcA custom default configuration in

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

ESlint verification

The second block has configured the configuration file, but how to verify the file

Verify.js type files

// verify a.js and B.js
npx eslint a.js b.js 
// verify the SRC and scripts directories
npx eslint src scripts
Copy the code

Verify other types of files

In general, ESLint can only validate JS files. For example, to validate.vue files, it is not enough to simply configure the vue plugin and vue-eslint-Parser. You also need to have ESLint find the.vue file when looking for the file. ESLint provides –ext to specify which files to validate

npx eslint --ext .js,.vue src
Copy the code

Automatic repair of part of the verification error code

Rules list itemIf the 🔧 rule is marked in, it indicates that the rule can be repaired automatically.ESLintprovides--fix

Package. The json configuration scripts

{ 
    "scripts": { 
        "lint": "npx eslint --ext .js,.vue src"."lint:fix": "npx eslint --fix --ext .js,.vue src",}}Copy the code

Filter some files that do not require verification

For some common JS, test scripts, or files in a specific directory, validation is not required by convention, so you can configure this by creating an.eslintignore file in the project root directory and telling ESLint to ignore them during validation:

public/
src/main.js
Copy the code

Why use ESLint

1. Background:

Two points are summarized:

  • Keep code styles consistent: For every thousand programmers, there are a thousand code styles. In front-end development, there are several code style differences that are still being debated. If a project’s code style is different, you can imagine that as the project iterations grow, it becomes difficult to look at

    • Single or double quotation marks?
    • Do I need a semicolon at the end of a line?
    • Two Spaces or four Spaces?
  • Reduce code errors: Due to the flexibility of JavaScript, there can often be multiple ways to write the same code, which can also lead to collaborative differences. Also, there are some scripts that can lead to bugs that aren’t easy to find, or that don’t perform well and should be avoided during development

To solve this type of static code problem, each team needs a common JavaScript code specification that team members follow to write code. Of course, relying on people to guarantee code specifications is not reliable, so you need a tool to do so, and ESLint is one of those tools

Why not Prettier

Prettier also makes code look the same, some readers might say. Yes, Prettier can format code uniformly according to the rules she sets, but it is important to be clear that Prettier only formats code. ESLint can’t find hidden code quality problems that Prettier cannot find.

3, goals,

Prompt when developing, automatic repair when saving, detection when submitting

V. Project practice

1. Vue-cli creation project

// package.json
 "devDependencies": {
    "@vue/cli-plugin-babel": "~ 4.5.0." "."@vue/cli-plugin-eslint": "~ 4.5.0." "."babel-eslint": "^ 10.1.0"."eslint": "^ 6.7.2." "."eslint-plugin-vue": "^ 6.2.2." ",},"eslintConfig": {
    "root": true."env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential".// equivalent to using eslint-plugin-eslint/essential
      "eslint:recommended",]."parserOptions": {
      "parser": "babel-eslint" / / the parser
    },
    "rules": {}},Copy the code

ESLint is supported in VSCode

The previous configuration requires executing commands to check and repair the code, which is still quite inconvenient. What if I want to check the code after editing or saving it? You can install the ESLint plugin directly into the IDE

  • Find a gear ⚙ icon in the lower left corner of VSCode, click and select Settings, this time opens the Settings panel;
  • Find the open Settings (json) icon in the upper right corner of VSCode and click on it to open the settings.json file.
  • Then paste in the following configuration;
{
    "eslint.alwaysShowStatus": true.// always display ESLint status in VSCode
    "eslint.quiet": true.// Ignore the error warning
    "editor.codeActionsOnSave": {     // Save using ESLint fixes fixes errors
        "source.fixAll": true."source.fixAll.eslint": true}}Copy the code

3, pre – commit

Two background

  • So that’s just throughESLintAutofix fixes errors that can be fixed by code formatting, but will inevitably be encountered during actual developmentAn error that cannot be fixedThe developer may also forget to make changes, and if the code is committed to a remote repository, the bad code is committed
  • When using commands to repair, you accidentally modify someone else’s code, which can easily cause conflicts. If a project has never used Linter before, how is it easiest to start using it and leave the previous code as untouched as possible?

One solution to these problems is to automatically fix formatting problems when you submit code, and only fix your changes

You can do this by configuring the pre-commit hooks of Git hooks. Husky and Lint-staged packages were primarily used.

  • Husky: Used to configure Git hooks
  • Lint – staged: getstagedFile processing
 "lint-staged": {
    "**/*.{js,vue}":  [
      "eslint --fix"."git add"]."**/*.{less,css,vue}":  [
      "stylelint --config ./.stylelintrc --fix"."git add"]},"husky": {
    "hooks": {
      "pre-commit": "lint-staged"}}Copy the code

reference

  • zhuanlan.zhihu.com/p/40730212
  • Juejin. Cn/post / 697422…