ESLint profile

ESLint is a code-checking tool that recognizes ECMAScript and reports on rules to avoid low-level errors and unify code styles. If esLint code is checked every time before code is submitted, the service will not crash because a field is not defined as undefined or null, and the quality of the project code can be effectively controlled.

In many ways, it is similar to JSLint and JSHint, with a few exceptions:

  • ESLint uses Espree to parse JavaScript.
  • ESLint uses AST to analyze patterns in code.
  • ESLint is fully plug-in. Each rule is a plug-in and you can add more rules at run time.

use

The installation

ESLint can be installed in a variety of ways, from NPM to webpack(eslint-loader) and gulp.js (gulp-ESLint).

Global installation

npm i -g eslint
Copy the code

Partial installation (recommended)

npm i -D eslint
Copy the code

Initialize the

After the installation is complete, create a new configuration file. Eslintrc.js, or use the following command line to generate it automatically:

eslint --init
Copy the code

configuration

Note: If you are using a version earlier than 1.0.0, please check the migration guide. After running eslint –init, the.eslintrc file will be automatically created in your folder. The content of the document is as follows:

{
    "env": {
        "es6": true."node": true
    },
    "extends": "eslint:recommended"."parserOptions": {
        "sourceType": "script"
    },
    "rules": {
        "no-console": 0."no-unused-vars": "error"."no-use-before-define": "error"."linebreak-style": [
            "error"."unix"]."quotes": [
            "error"."single"]."semi": [
            "error"."always"]."curly": ["error"."all"]."default-case": "error"."no-else-return": "error"."no-empty-function": "error"."no-implicit-coercion": "error"."no-invalid-this": "error"."no-loop-func": "error"."no-multi-spaces": "error"."no-new-func": "error"."no-useless-return": "error"."global-require": "error"."no-path-concat": "error"."no-sync": "error"."array-bracket-spacing": [
            "error"."never"]."block-spacing": [
            "error"."always"]."brace-style": [
            "error"."1tbs"]."camelcase": "error"."comma-dangle": [
            "error"."always-multiline"]."comma-spacing": [
            "error",
            { "before": false."after": true}]."comma-style": [
            "error"."last"]."key-spacing": [
            "error", 
            { "beforeColon": false."afterColon": true}]."lines-around-comment": [
            "error",
            { "beforeBlockComment": true}]."newline-after-var": [
            "error"."always"]."newline-before-return": "error"."no-multi-assign": "error"."max-params": [1, 3],
        "new-cap": [
            "error",
            {
                "newIsCap": true."capIsNew": false}]."no-multiple-empty-lines": [
            "error",
            {
                "max": 2}],"no-shadow-restricted-names": "error"."no-undef-init": "error"."keyword-spacing": "error"."space-before-blocks": [
            "error"."always"]}}Copy the code

The configurable information supported by ESlint falls into three main categories:

  • Environments: What Environments Javascript footsteps will run in (e.g. Nodejs, Browser, CommonJS, etc.). All Environments supported by ESlint can be found on the website.
  • Globals: Additional global variables that footsteps need to access when executing code.
  • Rules: Enables certain Rules and sets the level of Rules.

Detection rules

Next, you can set some rules in the configuration file. There are three levels of ESLint rules:

  • “Off” or 0: turns off the rule.
  • “Warn” or 1: opens the rule as a warning (does not affect exit code).
  • “Error” or 2: Opens the rule as an error (exit code will be 1).

For example, here are some configuration rules:

  • "console":"off"Disable the console.
  • "no-unused-vars":2Disallow unused variables.
  • "no-use-before-define":2It is not allowed to use variables before they are defined.
  • "linebreak-style":[2, "unix"]Enforce consistent line breaks.
  • "quotes": ["error", "single"]Enforces consistent single quotes.
  • "semi":["error", "always"]Control line tail semicolon.
  • "curly":["error", "all"]Force all control statements to use a consistent parenthesis style.
  • "default-case": "error"The switch statement enforces the default branch, or you can add a // no default comment to cancel the warning.
  • "no-else-return":"error"Disallow return followed by else in if statements.
  • "no-implicit-coercion": "error"Disallow null functions. If a function contains a comment, it will not be considered problematic.
  • "no-invalid-this": "error"Disallow the this keyword outside of classes and class objects.
  • "no-loop-func":"error"Disallow function declarations and expressions in loops.
  • "no-multi-spaces":"error"Disallow multiple Spaces.
  • "no-new-func":"error"Disallow the new operator on empty Function objects.
  • "no-useless-return":"error"Disallow returns without any content;
  • "global-require": "error"Require require() to appear in the top-level module scope.
  • "no-path-concat": "error"Disallow string concatenation of dirname and filename
  • "no-sync": "error"Disable the synchronization method.
  • "array-bracket-spacing": ["error", "never"]Specify that the elements of the array are separated by Spaces (, followed by), that the never argument cannot be followed by Spaces, and that the always argument must be followed by Spaces.
  • "block-spacing": ["error", "always"]Disallows or enforces the use of Spaces in single-line blocks of code (disabled).
  • "brace-style": ["error", "1tbs"]
  • "camelcase": "error"Mandatory hump naming.
  • "comma-dangle": ["error", "always-multiline"]Array and object key-value pairs last comma, never argument: cannot have trailing comma,always argument: must have trailing comma,always-multiline: must have comma, single-line mode: cannot have comma number.
  • "comma-spacing": ["error", { "before": false, "after": true }]Controls the space before and after commas.
  • "comma-style": ["error", "last"]Controls whether the comma appears at the end of the line or at the beginning of the line (the default line end).
  • "key-spacing": ["error", { "beforeColon": false, "afterColon": true }]This rule specifies that in object literal syntax, the space between key and value should not be preceded by a colon, but should be followed by a space.
  • "lines-around-comment": ["error", { "beforeBlockComment": true }]Requires empty lines around comments (requires empty lines before block-level comments).
  • "newline-after-var": ["error", "always"]A blank line after the var declaration statement is required or disallowed.
  • "newline-before-return": "error"Require an empty line before the return statement.
  • "no-multi-assign": "error"Assignments of linked variables can result in unexpected results and are difficult to read, and multiple assignments in a single statement are not allowed.
  • "max-params": [1, 3] functionThe maximum number of arguments allowed in the definition.
  • "new-cap": ["error", { "newIsCap": true, "capIsNew": false}]Constructor starts with a capital letter.
  • "no-multiple-empty-lines": ["error", {"max": 2}]Blank lines cannot exceed 2 lines.
  • "no-shadow-restricted-names": "error"Disallow assignment of keywords or reserved words such as NaN, Infinity, undefined, eval, arguments, etc.
  • "no-undef-init": "error"Disallow assigning undefined to a variable.
  • "keyword-spacing": "error"Spaces are required before and after the keyword.
  • "space-before-blocks": ["error","always"]Enforces consistent whitespace before blocks.

Ignore the detection

Since there are rules for detection, there must be configurations that ignore detection. To add a rule to ignore detection, first create an.eslintignore file in the project root to tell ESLint to ignore files or directories that do not need to be detected.

Or set objects to be ignored through package.json files, for example:

{
  "name": "my_project"."version": "1.0.0"."main": "index.js"."scripts": {
    "test": ""
  },
  "eslintConfig": {// Eslint can also be configured"env": {
      "es6": true."node": true}},"eslintIgnore": ["test.js"]}Copy the code

ESLint is used in Gulp

In addition to NPM, ESLint also supports the Gulp plugin, which you need to install before using.

npm install gulp-eslint
Copy the code

If you want to use gulp-ESLint to verify ESLint rules, you can do the following:

var gulp = require('gulp');
var eslint = require('gulp-eslint');
gulp.task('lint'.function() {return gulp.src(['app/**/*.js']) // Specifies the verification path. pipe(esLint ({configFle:"./.eslintrc"})) // Use your eslint validation file.pipe (eslint.format())});Copy the code

ESLint skills

eslint-config-standard

Eslint-config-standard is a standard ESLint rule checking library, so simply installing the library eliminates the need to configure ESLint rules.

{
  "extends": "standard"
}
Copy the code

After completing the above steps, you can use the ESLint tool to verify the code in your project.

In the Vue project,.vue files are written in htML-like format and are not standard JavaScript files, so ESLint cannot directly identify the JavaScript code in the Vue file.

 npm i eslint-plugin-html -D
Copy the code

This plugin is used to identify the JavaScript code inside the script tag in a vue file, and is officially recommended as such. So we’re going to add a script to the.eslintrc file:

{
  "extends": "standard"."plugins": [
    "html"]}Copy the code

After the above steps, go to scripts in package.json and add a command:

"lint": "eslint --ext .js --ext .jsx --ext .vue src/"

Copy the code

Ext (.js,.jsx,.vue, etc.); SRC (SRC /); ext (.js,.jsx,.vue);

Now we can go to Terminal and type $NPM run Lint to verify that the code in the project conforms to ESLint’s rules.

ESLint automatically fixes errors

In general, when we use the command “NPM run lint” to check JavaScript, there will be a lot of errors, basically full screen of errors and warnings.

"lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"

Copy the code

$NPM run lint-fix: $NPM run lint-fix: $NPM run lint-fix: $NPM run lint-fix: $NPM run lint-fix: $NPM run lint-fix:

/* eslint-disable */ on the first line of the JS file that reported the error, see Command Line Interface

eslint-loader

Sometimes you want ESLint to be checked automatically every time you change code during project development. Because we do a check as we change the code, if there is an error, we can quickly locate the problem and fix it. In this case we can use the eslint-Loader plug-in.

npm i eslint-loader babel-eslint -D
Copy the code

After the installation, we also need to configure the following script in the.eslintrc file:

{
  "extends": "standard"."plugins": [
    "html"]."parser": "babel-eslint"
}

Copy the code

Why did we configure Parser? Because our project is based on WebPack, all the code in the project needs to be processed by Babel. The syntax handled by Babel may not be particularly supportive of ESLint, and there will be some problems when we use loader to handle ESLint. So in general, projects we develop using Webpack and Babel specify that their parser uses babel-esLint.

For projects built using webpack, add the following script to the rules module of webpack.config.base-js:

rules: [
  {
    test: /\.(vue|js|jsx)$/,
    loader: 'eslint-loader',
    exclude: /node_modules/,
    enforce: 'pre'},... ]Copy the code

ESLint error detection can then be done in the development environment using the command $NPM run dev.

Add: cn.eslint.org/ www.imooc.com/article/322…