Use eslint + husky + lint staged + prettier to improve front-end project quality and unify project code style

Use eslint + husky + lint staged + prettier to improve front-end project quality and unify project code style

  • Eslint Check the code. After the editor enables Eslint, those that do not meet the specifications will be prompted automatically.
  • Prettier If you make the code pretty, you will change the code that does not meet the detection requirements and format it automatically.
  • husky git will execute the corresponding hook function for each operation without executing any operation. When executing the pre commit operation, execute the Prettier formatting script to automatically format the code, so that the code after the commit conforms to the Prettier specification.
  • lint-staged If you suddenly add a formatting tool to a project with a certain scale, will the whole project change? Lint staged is used to process only changed files

Installation dependency

npm i -D husky lint-staged prettier eslint-plugin-prettier eslint-config-prettier

to configure. eslintrc (this is just an example, which is configured according to the project)

  "extends": ["airbnb", "prettier"],
  "parser": "babel-eslint",
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module"
  "rules": {
    "space-in-parens": [0],
    "no-tabs": [0],
    "global-require": [0],
    "react/jsx-filename-extension": [0],
    "indent": ["error", 2],
    "react/jsx-indent": [0],
    "jsx-a11y/anchor-is-valid": [0],
    "import/extensions": [0],
    "react/jsx-curly-spacing": [0],
    "react/jsx-tag-spacing": [0],
    "react/require-default-props": [0],
    "class-methods-use-this": ["off"],
    "arrow-body-style": ["warn", "always"],
    "padded-blocks": ["off"],
    "no-trailing-spaces": ["error", { "ignoreComments": true }],
    "react/jsx-indent-props": [0],
    "no-nested-ternary": ["error"],
    "no-underscore-dangle": ["off", "always"],
    "prefer-destructuring": ["warn"],
    "camelcase": ["warn"],
    "no-irregular-whitespace": ["warn"],
    "jsx-a11y/no-static-element-interactions": [0],
    "jsx-a11y/click-events-have-key-events": [0],
    "no-return-assign": ["off"],
    "consistent-return": ["error", { "treatUndefinedAsUnspecified": true }],
    "dot-notation": ["warn"],
    "linebreak-style": "off",
    "quotes": ["error", "double"],
    "no-console": ["warn", { "allow": ["warn", "error", "log"] }],
    "import/no-useless-path-segments": "off",
    "object-curly-newline": "off",
    "no-shadow": "off",
    "react/jsx-one-expression-per-line": "off",
    "jsx-a11y/label-has-associated-control": "off",
    "jsx-a11y/label-has-for": "off",
    "max-len": ["error", { "code": 100 }]

Profile description

ESLint supports several formats of configuration files
  • JavaScript - use eslintrc.js and then output a configuration object.
  • YAML - use eslintrc.yaml or eslintrc.yml to define the configuration structure.
  • JSON - use eslintrc.json to define the configuration structure. ESLint's JSON file allows JavaScript style annotations.
  • (deprecated) - use eslintrc, which can make JSON or YAML.
  • package.json - in package Create an eslintConfig attribute in JSON and define your configuration there.

If there are multiple configuration files in the same directory, ESLint will only use one. The priority order is as follows:

  1. .eslintrc.js
  2. .eslintrc.yaml
  3. .eslintrc.yml
  4. .eslintrc.json
  5. .eslintrc
  6. package.json
Globals - configure additional global variables

When the ESLint rule is enabled, the no undef rule will issue a warning when accessing variables that are not defined in the current source file.
Sometimes, we need to access some global variables in other files and ensure that the values can be obtained normally. At this time, you can define these global variables in ESLint so that ESLint will not issue a warning.

  • Specify global variables with comments in the following format:
/* global var1, var2 */

This defines two global variables, var1 and var2. If you want to selectively specify that these global variables can be written (rather than just read), you can set them with a "writable" flag:

/* global var1:writable, var2:writable */

In the configuration file, set the global configuration attribute setting. For each global variable key, set the corresponding value to "writable" to allow the variable to be rewritten, or "readonly" does not allow the variable to be rewritten. For example:

// .eslintrc.js
"globals": {
  "var1": "writable",
  "var2": "readonly"
Environments - specifies the environment in which the script runs

Each environment has a specific set of predefined global variables. Such as brower, node environment variable, es6 environment variable, etc.

'env': {
  'browser': true,
  'commonjs': true,
  'es6': true
Plugins - third party plug-ins

ESLint supports the use of third-party plug-ins. First download and install the plug-ins to be introduced in the project. The plugins keyword is used in the configuration file to store the list of plug-in names. The ESLint plugin prefix can be omitted from the plug-in name.

 plugins: ['react', 'babel'], // eslint-plugin-react eslint-plugin-babel
Extensions - inheritance

A configuration file can be inherited by enabled rules in the basic configuration.

 extends: ["eslint:recommended","plugin:prettier/recommended"],

The code specification is configured to ensure the implementation of the specified code specification. The common code specifications of some large manufacturers are Ali's front end specificationairbnbGoose factory alloyteam team

Configure code annotation method

Sometimes, we need to ignore some rule checks of ESLint in the code. At this time, we can solve it by adding code comments: we can specify the whole file, a line and a block to turn on / off some or all rule checks;

/* eslint-disable */    --If all rules are disabled and placed at the top of the file, the entire file range is not checked
/* eslint-disable no-alert, no-console */  --Disable some rules
// Eslint disable line -- Disable rule on current line
// Eslint disable next line -- Disable rule on next line
Rules - enabled rules and their respective error levels

ESLint comes with a number of rules. You can use comments or configuration files to modify the rules to be used in your project. To change a rule setting, you must set the rule ID to one of the following values:

  • 'off' or 0 - close rule
  • "Warn" or 1 - turn on the rule, error with warning level: warn (will not cause the program to exit)
  • "Error" or 2 - open the rule and use the error level error: error (when triggered, the program will exit)
Common rule errors complete rule view Official documents
"no-alert": 0,//alert confirm prompt is prohibited
"no-array-constructor": 2,//Array constructors are prohibited
"no-bitwise": 0,//Bitwise operators are prohibited
"no-caller": 1,//Do not use arguments Caller or arguments callee
"no-catch-shadow": 2,//Prohibit catch clause parameters from having the same name as external scope variables
"no-class-assign": 2,//Prohibit assigning values to classes
"no-cond-assign": 2,//Assignment statements are prohibited in conditional expressions
"no-console": 2,//console is prohibited
"no-const-assign": 2,//Modifying variables declared by const is prohibited
"no-constant-condition": 2,//Prohibit constant expression if(true) if(1) in condition
"no-continue": 0,//Do not use continue
"no-control-regex": 2,//Prohibit the use of control characters in regular expressions
"no-debugger": 2,//Disable debugger
"no-delete-var": 2,//You cannot use the delete operator on variables declared by var
"no-div-regex": 1,//Regular expressions that look like division / = foo cannot be used/
"no-dupe-keys": 2,//Key repetition {a:1,a:1} is not allowed when creating an object literal
"no-dupe-args": 2,//Function parameters cannot be repeated
"no-duplicate-case": 2,//The case label in switch cannot be repeated
"no-else-return": 2,//If there is a return in the if statement, it cannot be followed by an else statement
"no-empty": 2,//The content in a block statement cannot be empty
"no-empty-character-class": 2,//[] content in regular expression cannot be empty
"no-empty-label": 2,//It is forbidden to use empty label
"no-eq-null": 2,//Do not use = = or for null= operator
"no-eval": 1,//Do not use eval
"no-ex-assign": 2,//Assigning values to exception parameters in catch statements is prohibited
"no-extend-native": 2,//Prohibit extending native objects
"no-extra-bind": 2,//Prohibit unnecessary function binding
"no-extra-boolean-cast": 2,//Prohibit unnecessary bool conversion
"no-extra-parens": 2,//Unnecessary parentheses are prohibited
"no-extra-semi": 2,//Prohibit redundant colons
"no-fallthrough": 1,//Prohibit switch penetration
"no-floating-decimal": 2,//It is forbidden to omit 0.5.3 in floating-point numbers
"no-func-assign": 2,//Duplicate function declarations are prohibited
"no-implicit-coercion": 1,//Prohibit implicit conversion
"no-implied-eval": 2,//Implicit eval is prohibited
"no-inline-comments": 0,//Intra line remarks are prohibited
"no-inner-declarations": [2, "functions"],//The use of declarations (variables or functions) in block statements is prohibited
"no-invalid-regexp": 2,//Disable invalid regular expressions
"no-invalid-this": 2,//Invalid this is prohibited. It can only be used in constructors, classes and object literals
"no-irregular-whitespace": 2,//Irregular spaces are not allowed
"no-iterator": 2,//No use__ iterator__  attribute
"no-label-var": 2,//The label name cannot be the same as the variable name declared by var
"no-labels": 2,//Prohibition label declaration
"no-lone-blocks": 2,//Unnecessary nested blocks are prohibited
"no-lonely-if": 2,//Forbid else statements to contain only if statements
"no-loop-func": 1,//It is forbidden to use functions in loops (if there is no reference to external variables and no closure is formed)
"no-mixed-requires": [0, false],//Declaration types cannot be mixed when declaring
"no-mixed-spaces-and-tabs": [2, false],//It is forbidden to mix tab s and spaces
"linebreak-style": [0, "windows"],//Line feed style
"no-multi-spaces": 1,//You cannot use extra spaces
"no-multi-str": 2,//String cannot be wrapped with \
"no-multiple-empty-lines": [1, {"max": 2}],//There can be no more than 2 blank lines
"no-native-reassign": 2,//native objects cannot be overridden
"no-negated-in-lhs": 2,//The left side of the in operator cannot have!
"no-nested-ternary": 0,//Nested ternary operations are prohibited
"no-new": 1,//It is forbidden to use new to construct an instance without assignment
"no-new-func": 1,//new Function is prohibited
"no-new-object": 2,//Object new ()
"no-new-require": 2,//new require is prohibited
"no-new-wrappers": 2,//It is forbidden to use new to create wrapper instances. New string, new Boolean, new number
"no-obj-calls": 2,//You cannot call built-in global objects, such as Math() JSON()
"no-octal": 2,//Octal digits are prohibited
"no-octal-escape": 2,//Octal escape sequences are prohibited
"no-param-reassign": 2,//Re assignment of parameters is prohibited
"no-path-concat": 0,//Cannot be used in node__ Dirname or dirname__ filename for path splicing
"no-plusplus": 0,//It is forbidden to use + +--
"no-process-env": 0,//Process. Is prohibited env
"no-process-exit": 0,//Process. Is prohibited exit()
"no-proto": 2,//No use__ proto__ attribute
"no-redeclare": 2,//Repeated declaration of variables is prohibited
"no-regex-spaces": 2,//Prohibit multiple spaces in regular expression literals / foo bar/
"no-restricted-modules": 0,//If the specified module is disabled, an error will be reported
"no-return-assign": 1,//The return statement cannot have an assignment expression
"no-script-url": 0,//Disable javascript:void(0)
"no-self-compare": 2,//Cannot compare itself
"no-sequences": 0,//Comma operators are prohibited
"no-shadow": 2,//A variable in an external scope cannot have the same name as a variable or parameter in the scope it contains
"no-shadow-restricted-names": 2,//The restricted identifier specified in strict mode cannot be used as the variable name at the time of declaration
"no-spaced-func": 2,//When calling a function, there must be no space between the function name and ()
"no-sparse-arrays": 2,//Prohibit sparse arrays, [1,, 2]
"no-sync": 0,//nodejs disable synchronization method
"no-ternary": 0,//Ternary operators are prohibited
"no-trailing-spaces": 1,//There should be no spaces after the end of a line
"no-this-before-super": 0,//this or super cannot be used until super() is called
"no-throw-literal": 2,//It is forbidden to throw literal error throw "error";
"no-undef": 1,//Cannot have undefined variables
"no-undef-init": 2,//When initializing a variable, it cannot be directly assigned as undefined
"no-undefined": 2,//undefined cannot be used
"no-unexpected-multiline": 2,//Avoid multiline expressions
"no-underscore-dangle": 1,//Identifier cannot be in_ Start or end
"no-unneeded-ternary": 2,//Prohibit unnecessary nesting var isyes = answer = = = 1? true : false;
"no-unreachable": 2,//There can be no code that cannot be executed
"no-unused-expressions": 2,//Disable useless expressions
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//There cannot be variables or parameters that are not used after declaration
"no-use-before-define": 2,//Cannot be used before being defined
"no-useless-call": 2,//Unnecessary call s and applications are prohibited
"no-void": 2,//Disable void operator
"no-var": 0,//Disable var and replace it with let and const
"no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],//Warning remarks are not allowed
"no-with": 2,//Disable with
"array-bracket-spacing": [2, "never"],//Allow extra spaces in non empty array
"arrow-parens": 0,//Arrow functions are enclosed in parentheses
"arrow-spacing": 0,//=>Before / after parentheses
"accessor-pairs": 0,//Using getters / setters in objects
"block-scoped-var": 0,//Using var in block statements
"brace-style": [1, "1tbs"],//Brace style
"callback-return": 1,//Avoid calling callbacks many times
"camelcase": 2,//Mandatory hump naming
"comma-dangle": [2, "never"],//The end of an object literal item cannot have a comma
"comma-spacing": 0,//Space before and after comma
"comma-style": [2, "last"],//Comma style, at the beginning or end of the line when wrapping
"complexity": [0, 11],//Cyclic complexity
"computed-property-spacing": [0, "never"],//Is it allowed to calculate the key name or something
"consistent-return": 0,//Can you omit after return
"consistent-this": [2, "that"],//this alias
"constructor-super": 0,//Non derived classes cannot call super, and derived classes must call super
"curly": [2, "all"],//You must use {} in if() {}
"default-case": 2,//The switch statement must end with default
"dot-location": 0,//The position of the object accessor, whether it is at the beginning or end of the line when wrapping
"dot-notation": [0, { "allowKeywords": true }],//Avoid unnecessary square brackets
"eol-last": 0,//The file ends with a single line break
"eqeqeq": 2,//Congruence must be used
"func-names": 0,//Function expression must have a name
"func-style": [0, "declaration"],//Function style, which specifies that only function declarations / function expressions can be used
"generator-star-spacing": 0,//Spaces before and after generator function *
"guard-for-in": 0,//for in loop should be filtered with if statement
"handle-callback-err": 0,//nodejs processing error
"id-length": 0,//Variable name length
"indent": [2, 4],//Indent style 
"init-declarations": 0,//Initial value must be assigned when declaring
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],//Spaces before and after colons in object literals
"lines-around-comment": 0,//Remarks before / after line
"max-depth": [0, 4],//Nested block depth
"max-len": [0, 80, 4],//Maximum string length
"max-nested-callbacks": [0, 2],//Callback nesting depth
"max-params": [0, 3],//Function can have at most 3 parameters
"max-statements": [0, 10],//How many declarations are there at most in a function
"new-cap": 2,//The first line of the function name must be capitalized and called in new mode, and the first line of lowercase must be called without new
"new-parens": 2,//new must be enclosed in parentheses
"newline-after-var": 2,//Whether a blank line is required after variable declaration
"object-curly-spacing": [0, "never"],//Whether unnecessary spaces are allowed in braces
"object-shorthand": 0,//Enforce object literal abbreviation syntax
"one-var": 1,//declaration of continuity
"operator-assignment": [0, "always"],//Assignment operator + = - = something
"operator-linebreak": [2, "after"],//Is the operator at the end of the line or at the beginning of the line when wrapping
"padded-blocks": 0,//Whether the beginning and end of a line in a block statement should be blank
"prefer-const": 0,//const preferred
"prefer-spread": 0,//Preferred expansion operation
"prefer-reflect": 0,//Preferred method of Reflect
"quotes": [1, "single"],//Quote type ''
"quote-props":[2, "always"],//Whether double quotation marks are mandatory for attribute names in object literals
"radix": 2,//parseInt must specify the second parameter
"id-match": 0,//Name detection
"require-yield": 0,//Generator function must have yield
"semi": [2, "always"],//Statement force semicolon end
"semi-spacing": [0, {"before": false, "after": true}],//Space before and after semicolon
"sort-vars": 0,//Sort on variable declaration
"space-after-keywords": [0, "always"],//Do you want to leave a space after the keyword
"space-before-blocks": [0, "always"],//Do you want a space in front of a block {that does not start with a new line
"space-before-function-paren": [0, "always"],//Should there be spaces before parentheses when defining functions
"space-in-parens": [0, "never"],//Are there any spaces in parentheses
"space-infix-ops": 0,//Do you want spaces around infix operators
"space-return-throw-case": 2,//Do you want to add a space after return throw case
"space-unary-ops": [0, { "words": true, "nonwords": false }],//Do you want to add spaces before / after unary operators
"spaced-comment": 0,//Does the annotation style have spaces or something
"strict": 2,//Use strict mode
"use-isnan": 2,//NaN is prohibited for comparison. Only isNaN()
"valid-jsdoc": 0,//jsdoc rules
"valid-typeof": 2,//You must use a legal typeof value
"vars-on-top": 2,//var must be placed at the top of the scope
"wrap-iife": [2, "inside"],//The parenthesis style of the immediate execution function expression
"wrap-regex": 0,//Regular expression literals are enclosed in parentheses
"yoda": [2, "never"]//Prohibition of Yoda conditions

eslint extension

eslint command Reference link

eslint [options] file.js [file.js] [dir]

Basic configuration: //Basic configuration
  --no-eslintrc                  Disable use of configuration from .eslintrc.* //It is forbidden to use from eslintrc.* Configuration file for
  -c, --config path::String      Use this configuration, overriding .eslintrc.* config options if present //If present eslintrc.*, The configuration file is used and rewritten
  --env [String]                 Specify environments //Specified environment
  --ext [String]                 Specify JavaScript file extensions - default: .js //Specified JS file extension, default: js
  --global [String]              Define global variables //Define global variables
  --parser String                Specify the parser to be used //Specifies the use of a parser
  --parser-options Object        Specify parser options //Specify resolution parameters

Specifying rules and plugins: //Specify rules and plug-ins
  --rulesdir [path::String]      Use additional rules from this directory //Use additional rules from this path
  --plugin [String]              Specify plugins //Specify plug-ins
  --rule Object                  Specify rules//Specify rules

Fixing problems://Fix the problem
  --fix                          Automatically fix problems//Automatically fix problems
  --fix-dry-run                  Automatically fix problems without saving the changes to the file system//Automatically fix problems without saving changes to the file system

Ignoring files: //Ignore file
  --ignore-path path::String     Specify path of ignore file //Specifies the file to ignore
  --no-ignore                    Disable use of ignore files and patterns //Do not use ignore files and styles
  --ignore-pattern [String]      Pattern of files to ignore (in addition to those in .eslintignore) //File patterns to ignore (except for files in. eslintignore)

Using stdin: //unix] standard input (device) file
  --stdin                        Lint code provided on <STDIN> - default: false
  --stdin-filename String        Specify filename to process STDIN as //Specifies the file name used to process stdin

Handling warnings://Processing warnings
  --quiet                        Report errors only - default: false //Report only as errors
  --max-warnings Int             Number of warnings to trigger nonzero exit code - default: -1 //Number of warnings to trigger non-zero exit codes - default: - 1
  -o, --output-file path::String  Specify file to write report to //Specifies the file path for the output
  -f, --format String            Use a specific output format - default: stylish //Use a specific output format - default: stylish
  --color, --no-color            Force enabling/disabling of color

Inline configuration comments: //Inline configuration comments
  --no-inline-config             Prevent comments from changing config or rules //Prevent comments from changing configuration or rules
  --report-unused-disable-directives  Adds reported errors for unused eslint-disable directives //Adds a reported error for an unused eslint disable directive

  --cache                        Only check changed files - default: false //Check only changed files
  --cache-file path::String      Path to the cache file. Deprecated: use --cache-location - default: .eslintcache//The path to the cache file. Deprecated: use -- cache location - default: eslintcache
  --cache-location path::String  Path to the cache file or directory//The path to the cache file or folder

  --init                         Run config initialization wizard - default: false //Run the configuration initialization Wizard - default: false
  --debug                        Output debugging information//Output debugging information
  -h, --help                     Show help 
  -v, --version                  Output the version number
  --print-config path::String    Print the configuration for the given file//Print the configuration of the given file

Create in the root directory editorconfig file, add the following configuration

root = true

# explain
## Set the file code to UTF-8;
## Replace tabs with two spaces;
## Delete the trailing white space character when saving;
## Add a blank line at the end of the file;
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

trim_trailing_whitespace = false

indent_style = tab

The EditorConfig project contains a file format that defines the encoding style and a collection of text editor plug-ins that enable the editor to read the file format and follow the defined style.

  1. The configuration of. editorconfig helps multiple developers working on the same project maintain a consistent coding style across multiple editors and ides.
  2. Some editors have integrated support for EditorConfig by default, such as Webstorm, IntelliJ IDEA, etc;
  3. Other editors need to be supported by installing corresponding plug-ins: such as Visual Studio Code, Atom, etc;
    The required plug-in for our common Visual Studio Code installation: EditorConfig for VS Code

to configure. prettierrc

Specific rules Reference official website

  // Set mandatory single quote
  "singleQuote": true,
  // Adding commas es5 to non trailing lines of a multiline array, objects, arrays, etc
  "trailingComma": "es5",
  // Maximum width per row 100
  "printWidth": 100,
  // Sets the end of a statement without a semicolon
  "semi": false,
  // Use single quotation marks in jsx
  "jsxSingleQuote": true,

Configure husky

npm i husky -D(Check if the installation fails node Version, required node10 Above)

Husky's configuration can be used huskyrc,. huskyrc.json,. huskyrc.js or husky config. JS file.
This is introduced in package JSON adds the following configuration:

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"

Configure lint staged

This is introduced in package JSON adds the following configuration:

"lint-staged": {
  "src/**/*.js": [
    "eslint --fix --ext .js",
    "prettier --write",
    "git add"

Tags: Javascript node.js html5 Vue Code Style IDE

Posted by helppy on Sun, 01 May 2022 15:47:01 +0300