What is a eslint

ESLint is a code-checking tool that checks whether your code conforms to specified specifications (e.g. : = must have a space before and after it).

  • specification

    • Industry-recommended specifications; When creating the project, we use JavaScript ==Standard== Style code Style rules
    • Custom specifications. You and your team can agree on your own set of norms
  • The advantage of using ESLint is that the code style is uniform when multiple people collaborate

Eslint is the judge, Standard is the lawCopy the code

The vue-CLI tool provides an option when creating a project, which we selected earlier when creating the project, so it takes effect directly in this project.

JavaScript Standard Style specifications

We selected this specification at the beginning of the project, which means that all of our subsequent code must comply with this requirement or ESLint will report errors.

Here are a few of the rules:

  • Strings use single quotes– Except for places that need to be escaped
  • Add Spaces after the keyword if (condition) { ... }
  • Function names are followed by Spaces function name (arg) { ... }
  • Stick to congruence= = =Slam the door= =Once you need to checknull || undefinedCan be usedobj == null
  • .

Suggested github.com/standard/st… Look it over, and then when you encounter an error while writing, you can query and solve it. If you cannot find the rules Look at here: www.verydoc.net/eslint/0000…

Code specification error

Eslint will tell you if your code doesn’t meet standard requirements. Let’s make some arbitrary 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 = New Vue({router, render: h => h(App)}).$mount('# App ')Copy the code

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

Four ways to correct mistakes

There are four ways to correct errors:

  • Manual correction: Human modification
  • Command modification: NPM run lint
  • Modify the rules: make the code conform to the modified rules so that no errors are reported
  • Plugin fix: works with the eslint plugin in vscode

Manual correction

Follow the error prompts to manually correct item by item.

If you don’t know what the syntax on the command line means, you can use the error rule names (fun-call-spacing, space-in-parens,…..) Go to the ESLint rule list website to find the exact meaning.

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

Command correction

Vuecli provides automatic repair when creating a project (some complex errors still need to be corrected manually) by running:

npm run lint
Copy the code

summary

There are four ways to fix esLint errors: we cover the first two here and the second two separately.

ESLint- Custom rules

The target

Understand custom rules of ESLint and can understand the configuration of.eslintrc.js

Custom check

Under the root of the project, there is a.eslintrc.js file that configates ESLint with a property that sets custom code rules: rules

Module. Exports = {root: true, / / the current project using this configuration file, not to find the parent directory. Eslintrc. Env js file: {// Specifies the esLint startup environment (vuecli is supported by Node). Browser: true can also be set in the browser to node: true}, extends: [// extend configuration 'plugin:vue/essential', // make eslint inherit @vue/cli scaffolding -standard '], parserOptions: {// Use esLint parser for the new syntax: 'babel-eslint' // use babel-eslint to parse the new syntax ES6}, // here you can configure custom rules // key: rule code name // value: Specific qualification // "off" or 0 - close the rule // "WARN" or 1 - treat the rule as a warning (does not affect the exit code), only warn, do not exit the program // "error" or 2 - Treat the rule as an error (exit code 1), Rules: {// Custom rules - There are a lot of built-in rules that can be changed here 'no-console': Process.env.node_env === 'production'? 'warn' : 'off', Process.env.node_env === 'production'? 'warn' : 'off', // Debugger can terminate code execution of 'no-multiple-empty-lines': 'off' // no consecutive blank lines allowed (off rule)}}Copy the code

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

  • The key name is the rule name (available in error messages and on esLint’s website)
  • Values are the specifications for this rule, most commonly off, WARN, and error.

Example – Turn off multi-line whitespace

Add a configuration item to the configuration file:

// omit other + 'no-multiple-empty-lines': 'off' // do not allow consecutive blank lines (turn off the rule)}Copy the code

Modify the configuration file, be sure to restart the project, check the effect

ESLint- use plug-ins in vscode

The target

Learn how to work with the eslint plugin in vscode:

  1. Prompt immediately if there is an error (display wavy line)
  2. CTRL + S automatically corrects errors immediately when saved

A way to correct mistakes

There are three ways to correct errors:

  • Manual correction: Human modification
  • Command modification: NPM run lint
  • Plugin fix: works with the eslint plugin in vscode

Install the ESLint plugin

We can also install the eslint plugin and let vscode tell me in real time what I’m doing wrong

== very, very, very important == : when opening a project with vscode, use the scaffold project as the vscode root directory, since eslint uses the configuration file.eslintrc

Eslint automatically formats corrected code

Follow these five steps:

Here’s a sidebar:

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

Eslint.run – The time at which esLint validation is run (onSave save) (onType input)

Editor. codeActionsOnSave – Controls which problems are fixed when code actions are run at save time

  • Source.fixall. eslint – All auto-fixable ESLint errors from all plug-ins will be fixed at save time

More rules can be found here

Note: Possible problems

CTRL + S Save does not automatically format

Open a code file with ESLint in the bottom right corner. If so, click and select AnyWhere to effect AnyWhere in the pop-up dialog box.

“V” means it’s on

Auto indent 1

Try uninstalling Beautify plugins – esLint can also Beautify your codeThere may also be JS/CSS Format plug-ins/other beautification plug-ins ==

Do not want to uninstall can be disabled

If you enable automatic formatting in vscode with other extensions, you may run afoul of eslint’s rules!

Solution: turn off automatic formatting in vscode

Auto indent 2

If this does not work, change the configuration of vscode

File > Settings, search for this and uncheck the box below

One save, single lead change double lead

Cause: The vetur plugin conflicts with ESLint. Modify the ESLint plugin configuration to override this code

{ "eslint.run": "onType", "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "vetur.validation.template": False, // Remove the template from the vetur extension "editor.formatOnSave": False, // Get rid of vscode autosave, vscode is also false by default, if you want to use ESlint formatting, the default formatting will not enable" eslint.enable": AutoFixOnSave ": true, // eslint format configuration "eslint.autoFixOnSave": true, // ESlint saves automatically resolve syntax error "eslint.options": {// esLint option - Format js and vue files "Extensions ": [".js", ".vue"]}, "eslint.validate": ["javascript", {"language": "vue", "autoFix": true, }, "html", "vue" ], }Copy the code