Basic introduction of ESLint

Posted by jonnypixel on Mon, 18 Oct 2021 22:44:27 +0200

What is eslint

ESLint Is a code checking tool used to check whether your code meets the specified specifications (for example, there must be a space before and after =).

  • standard

    • Industry recommended specifications; When creating the project, we use the rules of JavaScript Standard Style code style
    • Custom specification. You and your team can agree on a set of specifications
  • The advantage of using ESLint is that the code style is unified when multiple people cooperate

eslint It's a judge, Standard It's the law

Vue cli tool provides options when creating a project. We selected it when creating a project, so it is directly effective in this project.

JavaScript Standard Style specification

We selected this specification at the beginning of the project creation, that is, all our subsequent codes must comply with this requirement, otherwise ESLint will report an error.

Here are a few of the rules:

  • Use single quotation marks for strings – except where escape is required
  • Keyword followed by a space if (condition) {...}
  • Function name followed by whitespace function name (arg) {...}
  • Insist on using congruence = = = discard = = one, but you can use obj == null when you need to check null | undefined
  • ...
    It is suggested that https://github.com/standard/standard/blob/master/docs/RULES-zhcn.md Read it again, and then you can query and solve the problem when you encounter an error in writing. If you can't find your rules, look here: http://www.verydoc.net/eslint/00003312.html

Code specification error

If your code does not meet the requirements of standard, eslint will jump out of the knife mouth and remind you heartily. Let's make some changes in main.js: add a line let a= 10;

import Vue from 'vue'
import App from './App.vue'
import router from './router'
​
Vue.config.productionTip = false
let a = 10 // This line of code is newly added
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

After pressing save code, you will see the following error output in the console:

Four ways to correct mistakes

There are four ways to correct errors:

  • Manual correction: human flesh modification
  • Command correction: npm run lint
  • Modification rules: make the code conform to the modified rules, and of course, no error will be reported
  • Plug in correction: cooperate with the eslint plug-in in vscode

Manual correction

Manually correct one by one according to the error prompt.

If you don't know what the syntax error in the command line means, you can find its specific meaning in the ESLint rule list website according to the name of the error rule (func call spacing, space in parens,...).

It is recommended that you manually modify errors to help develop good coding habits and be more professional

Command correction

vuecli provides an automatic repair function when creating a project (some complex errors still need to be corrected manually). The specific method is to run:

npm run lint

Summary

There are four ways to correct eslint errors: the first two are introduced here, and the latter two are introduced separately.

ESLint - custom rules

target

Understand the custom rules of eslint and the configuration of. eslintrc.js

Custom verification

Under the root directory of the project, there is a. eslintrc.js file, which configures eslint, and one attribute is specially used to set custom code rules: rules

module.exports = {
  root: true, // The current project uses this configuration file and will not find the. eslintrc.js file in the parent directory
  env: { // Specify the eslint startup environment (node support at the bottom of vuecli). browser: true can also be set in the browser
    node: true
  },
  extends: [ // Extended configuration
    'plugin:vue/essential', // Necessary rules in vue
    '@vue/standard' // Make eslint inherit the - standard standard standard in @ vue/cli scaffold
  ],
  parserOptions: { // Use eslint for new syntax
    parser: 'babel-eslint' // Use Babel eslint to parse the new syntax ES6
  },
  // Custom rule configuration can be performed here
  // key: rule code
  // value: specific qualification method
  //    "off" or 0 - close rule
  //    "warn" or 1 - treat the rule as a warning (does not affect the exit code), only a warning and does not exit the program
  //    "error" or 2 - treat the rule as an error (exit code is 1), report an error and exit the program
  rules: { // Custom rules - in fact, there are many built-in rules after the above integration. You can modify the rules here
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', // The online environment reports a warning by printing, and the development environment closes this rule
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', // debugger can terminate code execution
    'no-multiple-empty-lines': 'off' // Multiple consecutive blank lines are not allowed (closing rule)
  }
}

Rules is an object that specifies rules in the form of key value pairs:

  • The key name is the rule name (which can be viewed in the error message and eslint official website)
  • Value is the specific description of this rule. The most common are off, warn and error.

Example - turn off multiline spaces

Add a configuration in the configuration file:

  rules: { // Custom rules - in fact, there are many built-in rules after the above integration. You can modify the rules here
    // Omit others
+   'no-multiple-empty-lines': 'off' // Multiple consecutive blank lines are not allowed (closing rule)
  }

If the configuration file is modified, the project must be restarted to accept the effect

ESLint - using plug-ins in vscode

target

Master how to work with the eslint plug-in in vscode:

  1. Prompt immediately if there is an error (display wavy line)
  2. ctrl+s automatically corrects errors when saving

Ways to correct mistakes

There are three ways to correct errors:

  • Manual correction: human flesh modification
  • Command correction: npm run lint
  • Plug in correction: cooperate with the eslint plug-in in vscode

Install the eslint plug-in

We can also install the eslint plug-in to let vscode tell me in real time what's wrong with me

Very important: when opening a project with vscode, take the scaffolding project as the root directory of vscode, because eslint uses the configuration file. eslintrc

eslint auto format fix code

Follow the following five steps:

Here are the supplementary contents:

{
  "eslint.enable": true,
  "eslint.run": "onType",
  "eslint.options": {
      "extensions": [
          ".js",
          ".vue",
          ".jsx",
          ".tsx"
      ]
  },
  "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
  }
}

eslint.run - the time when the eslint verification is run (onSave save) (when onType is entered)

editor.codeActionsOnSave - controls which problems are fixed when running code actions at save time

  • source.fixAll.eslint - all automatically repairable ESLint errors from all plug-ins will be fixed at save time

More rules can be seen here

Remarks: possible problems

ctrl+s save does not automatically format

Open a code file, and there is an ESLint in the lower right corner. If so, click it, and the dialog box pops up. Select AnyWhere to take effect AnyWhere (start ESLint in vscode)

Becoming v means starting

Auto indent 1

Try to uninstall the Beautify plug-in - eslint can also Beautify the code

There may also be JS/CSS Format plug-ins / other beautification plug-ins

If you don't want to uninstall, you can disable it

If you use other extensions in vscode to enable automatic formatting, it may conflict with the rules of eslint!

Solution: turn off automatic formatting in vscode

Auto indent 2

If not, modify the vscode configuration

In File > settings, search for this and remove the check box below

Single lead to double lead

Reason: vetur plug-in conflicts with eslint. Modify the eslint plug-in configuration and overwrite the code here

{
    "eslint.run": "onType",
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "vetur.validation.template": false, // Remove the template format of vetur extension
    "editor.formatOnSave": false, // Remove the auto save provided by vscode. Vscode is also false by default. If you want to format with eslint, the default format cannot be opened
    "eslint.enable": true, // eslint formatted configuration
    "eslint.autoFixOnSave": true, // Syntax errors are automatically resolved when eslint is saved
    "eslint.options": { // eslint option - Format js and vue files
        "extensions": [
            ".js",
            ".vue"
        ]
    },
    "eslint.validate": [
        "javascript",
        {
            "language": "vue",
            "autoFix": true,
        },
        "html",
        "vue"
    ],
}

Topics: Javascript Visual Studio Code