husky and lint staged are used in the project to check the code before git submission

Preface: in this article, we will introduce Husky and lint staged. If you think the author's writing is good, I hope to get your praise / collection / support. If you have different opinions, please leave a message in the comment area below.

husky: is a code submission hook. That is, before the code is submitted to the Git warehouse, we can do some pre checking or formatting here. We need to do these operations. We need a Git submission hook, which is simply a function triggered by the Git command.

Lint staged: it is a front-end file filtering tool. Is a tool that only filters out Git code staging files (committed files). Lint staged is just a file filter and won't format anything for you.

1, Installation related dependencies

Note: after successful installation, you will get the. husky directory.

cnpm install husky lint-staged -D

2, To enable Git hooks automatically after installation, edit package.json

npm set-script prepare "husky install"
There should be:
// package.json
{
  "scripts": {
    "prepare": "husky install"
  }
}

3, Configure lint staged in package.json

Note: the lint staged configuration here is that in the files to be submitted in git, all specified files in the src directory must execute the configured commands.

// package.json
{
   "lint-staged": {
    "src/**/*.{css´╝îscss,less}": [
      "git add" //Continue git process
    ],
    "src/**/*.{js,vue,jsx}": [
       "eslint --fix", // eslint detection and repair
       "git add" //Continue git process
    ]
  }
}

4, Execute the command to create a pre commit hook

Note: npx is a command issued after npm5.2. The official website says that it is "execute npm package binaries", which is the binary file for executing NPM dependent packages. npx is mainly used for auxiliary functions such as command line addressing, and NPM is management dependent. In short, we can use npx to execute various commands. npx official website

//Use lint statged to execute. Use local resources instead of downloading
npx husky add .husky/pre-commit "npx --no-install lint-staged" 

After executing the command, there will be a pre commit in the. husky folder (modifying the code is the command to check the code before submitting the code).

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

//Use lint statged to execute. Use local resources instead of downloading
npx --no-install lint-staged

Above, the adjustment of the hook for the custom husky directory is completed. All husky instructions under the current subdirectory will be executed through the. Husky directory.

4, Install configuration install eslint

1. Install eslint plugin react and other related dependencies

cnpm install eslint babel-eslint eslint-plugin-react eslint-plugin-import  -D

2. Create the ESlint configuration file. eslintrc.js

eslint --init

3.eslintrc.js file verification configuration

module.exports = {
  "env": {
    "browser": true,
    "commonjs": true,
    "es6": true
  },
  "parser": "babel-eslint",
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": 7,
    // Turn on experiment properties
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      // Modifier
      "experimentalDecorators": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "globals": {
    "__DEV__": false,
    "__dirname": false,
    "window": true,
    "define": true,
    "history": true,
    "location": true,
    "wxjs": true,
    "$": true,
    "WeixinJSBridge": true,
    "wx": true,
    "process": true,
    "qq": true,
  },
  "settings": {
    "react": {
      "version": "16.2.0",
    }
  },
  /**
   * "off" Or 0 - close rule
   * "warn" Or 1 - turn on the rule and use the error of 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)
   */
  "rules": {
    "no-cond-assign": 2,
    "no-console": [
      "error", {
        "allow": ["log", "warn", "error", "info"]
      }
    ],
    // Duplicate name parameters in function definition are prohibited
    "no-dupe-args": 2,
    // Prohibit duplicate key s in object literals
    "no-dupe-keys": 2,
    // Prohibit duplicate case labels
    "no-duplicate-case": 2,
    // Prohibit empty statement blocks
    "no-empty": 2,
    // Re assignment of parameters to catch clauses is prohibited
    "no-ex-assign": 2,
    // Prohibit unnecessary Boolean conversions
    "no-extra-boolean-cast": 2,
    // Unnecessary parentheses / / (a * b) + c are prohibited// report errors
    "no-extra-parens": 0,

    //Force all control statements to use a consistent bracket style
    "curly": [2, "all"],
    // The parameter of the forbidden catch clause has the same name as a variable in the outer scope
    "no-catch-shadow": 0,
    // Labels with the same name as variables are not allowed
    "no-label-var": 2,
    // Disable specific global variables
    "no-restricted-globals": 2,
    // var declaration is prohibited from having the same name as a variable in the outer scope
    "no-shadow": 0,
    // Prohibit overwriting restricted identifiers
    "no-shadow-restricted-names": 2,
    // Initializing variables to undefined is prohibited
    "no-undef-init": 2,
    // undefined is prohibited as an identifier
    "no-undefined": 0,
    // Variables are not allowed to be used before they are defined
    "no-use-before-define": 0,
    //
    // Style guide//
    //
    // The elements of the specified array should be separated by spaces (, after). The never parameter: [before and] cannot be followed by spaces, and the always parameter: [before and] must be followed by spaces
    "array-bracket-spacing": [2, "never"],
    // Disables or forces the use of spaces in single line blocks (disabled)
    "block-spacing": [1, "never"],
    //Force consistent indentation. When the second parameter is "tab", tab is used,
    // The {after if while function must be on the same line as if, in java style.
    "brace-style": [2, "1tbs", {
      "allowSingleLine": true
    }],
    // Controls the space before and after commas
    "comma-spacing": [2, {
      "before": false,
      "after": true
    }],
    // Controls whether commas appear at the end of a line or at the beginning of a line (default end of line)
    // http://eslint.org/docs/rules/comma-style
    "comma-style": [2, "last"],
    //'SwitchCase '(default: 0) forces the indentation level of the case clause in a switch statement
    // Whether spaces are required before [and after] when taking object attributes in square brackets. Optional parameters are never and always
    "computed-property-spacing": [2, "never"],
    // It is used to refer to the variable name pointing to this in the callback function. This in the arrow function can point to the outer caller, which should be useless
    // e.g [0,"self"] can only specify var that = this. self cannot point to any other value, and this cannot be assigned to any value other than self
    "consistent-this": [2, "self", "that", "_self", "_that", "me", "_this"],
    // Forces the use of named function expressions
    "func-names": 0,
    // Forced line wrap at end of file
    "eol-last": 2,
    "indent": [
      "error", 2
    ],
    //Requires or prohibits a space between a function identifier and its call
    "func-call-spacing": 2,
    // Forces consistent spacing between keys and values in the properties of object literals
    "key-spacing": [2, {
      "beforeColon": false,
      "afterColon": true
    }],
    // Requires a blank line around a comment (requires a blank line before a block level comment)
    "lines-around-comment": [2, {
      "beforeBlockComment": true
    }],
    "func-style": 0,
    // The maximum nesting depth of the forced callback function is 5 layers
    "max-nested-callbacks": [2, 5],
    // The specified identifier is prohibited
    "id-blacklist": 0,
    // Force the latest and maximum length of the identifier
    "id-length": 0,
    // The identifier is required to match a specified regular expression
    "id-match": 0,
    // Force the consistent use of double or single quotes in JSX properties
    "jsx-quotes": 0,
    // Force consistent spaces before and after keywords (required)
    "keyword-spacing": 2,
    // Forces the maximum length of a row
    "max-len": [2, 200, { "ignoreUrls": true }],
    // Force maximum rows
    "max-lines": 0,
    // Force the maximum number of parameters allowed in the function definition
    "max-params": [1, 5],
    // Forces the maximum number of statements allowed for a function block
    "max-statements": [1, 200],
    // Forces the maximum number of statements allowed in each row
    "max-statements-per-line": 0,
    // The constructor is required to be capitalized (it is required to call the function with the initial size when calling the new operator, and it is allowed to call the function with the initial capital without the new operator.)
    "new-cap": [2, {
      "newIsCap": true,
      "capIsNew": false
    }],
    // Parentheses are required when calling a parameterless constructor
    "new-parens": 2,
    // Requires or prohibits an empty line after a var declaration statement
    "newline-after-var": 0,
    // Array constructors are prohibited
    "no-array-constructor": 2,
    // Disable bitwise operators
    "no-bitwise": 0,
    // A blank line is required before the return statement
    "newline-before-return": 0,
    // Each call in the method chain is required to have a newline character
    "newline-per-chained-call": 1,
    // Disable continue statement
    "no-continue": 0,
    // Inline comments are prohibited after lines of code
    "no-inline-comments": 0,
    // if is prohibited from appearing as the only statement in else statements
    "no-lonely-if": 0,
    // Do not mix different operators
    "no-mixed-operators": 0,
    //Mixed indentation of spaces and tab s is prohibited
    "no-mixed-spaces-and-tabs": [
      "error", "smart-tabs"
    ],
    // Multiple blank lines are not allowed
    "no-multiple-empty-lines": [2, {
      "max": 2
    }],
    // Negative expressions are not allowed
    "no-negated-condition": 0,
    // Nested ternary expressions are not allowed
    "no-nested-ternary": 0,
    // Constructor of Object is prohibited
    "no-new-object": 2,
    // Unary operators + + and are prohibited--
    "no-plusplus": 0,
    // Specific syntax is prohibited
    "no-restricted-syntax": 0,
    // Spaces between function identifiers and parentheses are prohibited
    "no-spaced-func": 2,
    // Ternary operators are not allowed
    "no-ternary": 0,
    // Disable end of line spaces
    "no-trailing-spaces": 2,
    // Prohibit dangling underscore _bar in identifier
    "no-underscore-dangle": 0,
    // Prohibit the use of ternary operators when there are simpler alternative expressions
    "no-unneeded-ternary": 2,
    // Blank before prohibition attribute
    "no-whitespace-before-property": 2,
    // Requires or prohibits line breaks around var declarations
    "one-var-declaration-per-line": 0,
    // Requires or prohibits the use of simplified assignment operators where possible
    "operator-assignment": 0,
    // Force operators to use consistent line breaks
    "operator-linebreak": [2, "after", {
      "overrides": {
        "?": "before",
        ":": "before"
      }
    }],
    // Block filling is required or prohibited
    "padded-blocks": 0,
    // Requires object literal attribute names to be enclosed in quotation marks
    "quote-props": 0,
    // Force consistent backticks, double quotes, or single quotes
    "quotes": [2, "single", "avoid-escape"],
    // JSDoc comments are required
    "require-jsdoc": 0,
    // Require or prohibit the use of semicolons instead of ASI (this is what controls the end of line part number,)
    "semi": [2, "always"],
    // Force consistent spaces before and after semicolons
    "semi-spacing": 2,
    // The variables in the same declaration block are required to be arranged in order
    "sort-vars": 0,
    // Force consistent spaces before blocks
    "space-before-blocks": [2, "always"],
    // Force a consistent space before the left parenthesis of function
    "space-before-function-paren": [2, "always"],
    // Force consistent spaces within parentheses
    "space-in-parens": [2, "never"],
    // Spaces around operators are required
    "space-infix-ops": 2,
    // Force consistent spaces before and after unary operators
    "space-unary-ops": [2, {
      "words": true,
      "nonwords": false
    }],
    // Force consistent spaces / / or / * in comments
    "spaced-comment": [2, "always", {
      "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!"]
    }],
    // Unicode BOM required or prohibited
    "unicode-bom": 2,
    // Regular expressions are required to be enclosed in parentheses
    "wrap-regex": 0,
    //Lexical declarations (let, const, function, and class) are prohibited from appearing in case or default clauses
    "no-case-declarations": ["warn"],
    //
    // ES6. Related//
    //
    // Braces are required for the body of the arrow function
    "arrow-body-style": 2,
    // Requires parentheses for the arguments of the arrow function
    "arrow-parens": 2,
    "arrow-spacing": [2, {
      "before": true,
      "after": true
    }],
    // Forces consistent spaces around the * sign in the generator function
    "generator-star-spacing": [2, {
      "before": true,
      "after": true
    }],
    // Modifying variables declared by a class is prohibited
    "no-class-assign": 2,
    // Arrow functions are not allowed, where they can be confused by comparison
    "no-confusing-arrow": 0,
    // Modifying variables declared by const is prohibited
    "no-const-assign": 2,
    // Duplicate names are prohibited in class members
    "no-dupe-class-members": 2,
    // Only one import can be used per module
    "no-duplicate-imports": 2,
    // The symbol new operator is prohibited from being used with new
    "no-new-symbol": 2,
    // Allows you to specify the import when the module is loaded
    "no-restricted-imports": 0,
    // this or super is prohibited in constructors before calling super()
    "no-this-before-super": 2,
    // Suppress unnecessary calculation of text for performance key objects
    "no-useless-computed-key": 0,
    // let or const is required instead of var
    "no-var": 1,
    // Requires or prohibits the use of shorthand syntax for methods and properties in object literals
    "object-shorthand": 0,
    // The arrow function is required as a callback
    "prefer-arrow-callback": 0,
    // const is required to declare variables that will not be modified after declaration
    "prefer-const": 0,
    // It is required to use the Reflect method where appropriate
    "prefer-reflect": 0,
    // Extension operator is required instead of. apply()
    "prefer-spread": 0,
    // Requires a template literal instead of a string connection
    "prefer-template": 0,
    // Suggest using the rest parameters instead of arguments
    "prefer-rest-params": 0,
    // yield is required in the generator function
    "require-yield": 2,
    // Requires or disables the use of spaces around embedded expressions in template strings
    "template-curly-spacing": 1,
    // Force spaces around * in yield * expressions
    "yield-star-spacing": 2,
    // Force a consistent line break style
    "linebreak-style": [2, "unix"],
    //Enforce Boolean attribute symbols in JSX
    "react/jsx-boolean-value": 2,
    //Verify the position of the closing bracket in JSX
    // "react/jsx-closing-bracket-location": 1,
    //Strengthen or prohibit spaces within braces in JSX properties and expressions.
    "react/jsx-curly-spacing": [2, {
      "when": "never",
      "children": true
    }],
    //Verify that JSX has a key attribute in an array or iterator
    "react/jsx-key": 2,
    // Limit the maximum number of props on a single line in JSX
    "react/jsx-max-props-per-line": [1, {
      "maximum": 5
    }],
    //Prevent duplicate props in JSX
    "react/jsx-no-duplicate-props": 2,
    //  //Prevent the use of unwrapped JSX strings
    // "react/jsx-no-literals": 0,
    //Undeclared variables are prohibited in JSX
    "react/jsx-no-undef": 2,
    //PascalCase is mandatory for user-defined JSX components
    "react/jsx-pascal-case": 0,
    //Prevent reactions from being incorrectly marked as unused
    "react/jsx-uses-react": 2,
    //Prevent variables used in JSX from being incorrectly marked as unused
    "react/jsx-uses-vars": 2,
    //Prevent the use of setState in componentDidMount
    "react/no-did-mount-set-state": 2,
    //Prevent the use of setState in componentDidUpdate
    "react/no-did-update-set-state": 2,
    //Prevent the use of unknown DOM properties
    "react/no-unknown-property": 2,
    //Enforce ES5 or ES6 classes for React components
    "react/prefer-es6-class": 2,
    //Prevent loss of props validation in React component definitions
    // "react/prop-types": 1,
    //Prevent loss of React when using JSX
    "react/react-in-jsx-scope": 2,
    //Prevent additional end tags for components without children
    "react/self-closing-comp": 0,
    //Prohibit unnecessary bool conversion
    // "no-extra-boolean-cast": 0,
    //Prevent using array key as index in array traversal
    // "react/no-array-index-key": 0,
    //Do not use deprecated methods
    "react/no-deprecated": 2,
    //Force or prohibit spaces around the equal sign in JSX properties
    "react/jsx-equals-spacing": 2,
    "react/jsx-filename-extension": [2, {
      "extensions": [".js", ".jsx"]
    }],
    // Disable unused variables
    "no-unused-vars": 0,
  }
};

After completion, before each code submission, pre commit will intercept git's commit operation, and then run the lint staged command to detect the code. If any violation of the verification rules is detected, an error will be returned, resulting in git commit failure.

Execute git to see if the hook works

git add .
git commit -m "test"

How do you want to bypass code checking and submit code directly

git commit -m "test" --no-verify

Finally, let's review: if you think the author's writing is good, I hope to get your praise / collection / support. If you have different opinions, please leave a message in the comment area below.

Tags: git

Posted on Sun, 10 Oct 2021 22:04:21 -0400 by ihcra