The introduction

You can check your code before committing. If the code is not formatted, you can stop committing. If the code is not formatted, you can stop committing.

role

Eslint automatically formats the code for us when we submit it, then uses ESLint to check the code and automatically fix errors, reporting errors if they can’t be fixed. If an error is reported, the commit will not be committed.

More information about commitlint, husky, and ESLint can be found on the website.

  • commitlint: website.Making the warehouse
  • husky:Making the warehouse
  • eslint Chinese website

tool

  1. prettier. A popular code formatting tool, you can easily find various plugins in the editor to implement it, such as VSCode, Atom,webstom. It is used here to format the code before it is submitted.
  2. eslint. Code review tool. Eslint can do some of the formatting checking, but prettier already does it so PRETTY I don’t use ESLint’s formatting checking, just error checking.
  3. lint-staged. Execute custom instructions in your submitted file. Don’t let 💩 slip into your codebase. — Lint-passage

The installation

Install eslint

npm i -D eslint babel-eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
Copy the code

Install the prettier

npm install --save-dev prettier eslint-plugin-prettier eslint-config-prettierCopy the code

Install Husky and Lint-stage

yarn add husky@next  Install the latest version, so you don't need to configure scripts
yarn add lint-stageCopy the code

configuration

Configuration commitlint

Commitlint matches husky’s Commit message hook. When committing git version information, commitlint checks it according to the configured rules. If the rules are not met, commitlint will commit failure and prompt corresponding information.

Install commitLint dependencies

yarn add @commitlint/{cli,config-conventional}Copy the code

Create a new commitlint.config.js file

module.exports = {
    extends: ['@commitlint/config-conventional']};Copy the code

The @commitlint.config. js configuration file can add its own rules, and @commitlint.config-Conventional provides an official extension to the rules:

Build: The main purpose is to modify the submission of the project build system (e.g., Glup, Webpack, rollup configuration, etc.) Update document feat: New function Merge: Merge branch? of ? Style: Code changes that do not affect the logic of the program (whitespaces, indentation, missing semicolons, etc., without changing the logic of the code)test: Add a test case or update an existing test; revert: Roll back an earlier submission; chore: Another type that does not belong to the aboveCopy the code

Configure the package.json file

Add the husky field

"husky": {
    "hooks": {
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"}},Copy the code

test

git add .
git commit -m "foo: this will fail"Copy the code

Prettier configuration

  1. prettierCode formatting core
  2. eslint-plugin-prettier Plugin, which allows ESLint to check with the prettier rule and the –fix option Eslint prompts red lines like the previous one when the format is not correct.
  3. eslint-config-prettierPlugins, as I said beforeeslintThe plug-in for prettier closes rules that are unnecessary or might conflict with prettier.

Add the following configuration to eslintrc.json:

{
 "extends": ["airbnb"."plugin:prettier/recommended"],}Copy the code

This configuration does three things:

  1. makeeslint-plugin-prettierTo take effect
  2. Do not conform to theprettier/prettierError will be reported. It’s the red line in the previous screenshot.
  3. makeeslint-config-prettierTo take effect. It’s going to covereslintAnd in theprettierConflicting configurations.

Prettier Configuration file

A variety of prittier profiles are supported, as you can see here. I use the. Prettierrrc format because I tried other formats, but only the. Prettierrrc, VScode can recognize. To generate the configuration, you can directly use the try it out on the official website. The export configuration is in the lower left corner. The following configuration is basically all style requirements, specific can be configured according to personal preferences.

{
  "printWidth": 120, // The maximum number of characters in a line"tabWidth": 2, // Number of characters used by TAB"useTabs": false, // Whether to use TAB instead of space"semi": true// Whether to add a semicolon after each sentence"singleQuote": true, // Whether to use single quotes"jsxSingleQuote": false, // JSX whether to use single quotes"trailingComma": "all", // End the array with a comma."bracketSpacing": false, // {foo: xx}还是{ foo: xx }
  "jsxBracketSameLine": false, // look at the official website"arrowParens": "always"// Whether to use () for the shear function parameter}Copy the code

Configure the ESLint hook

.eslintrc.js

* Vue to enable ESLint basically doesn’t need to be configured, react can configure its own

module.exports = {
  parser: 'babel-eslint',
  plugins: ['react'],
  root: true,
  env: {
    browser: true,
    node: true,
    es6: true
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module'
  },
  globals: {
    document: true.localStorage: true,
    window: true,
    process: true,
    console: true,
    navigator: true,
    fetch: true,
    URL: true
  },
  rules: {
    'no-console': 'off'.'no-alert': 0, // Disable using alert Confirm prompt'no-var': 0, // disable var, useletAnd const instead of'no-catch-shadow': 2, // disallow the catch clause argument to have the same name as the outer scope variable'default-case': 2, // the switch statement must end with default'dot-notation': [0, { allowKeywords: true}], // Avoid unnecessary square brackets'no-constant-condition': 2, // Disallow constant expressions in conditionsif(true) if(1)
    'no-dupe-args': 2, // Function arguments must not be repeated'no-inline-comments': 0, // No remarks in the line'no-unreachable': 2, // Cannot have unexecutable code'no-unused-vars': [2, { vars: 'all', args: 'after-used'}}, // No variables or parameters that have not been used after recording'no-unused-expressions': 2, / / ban useless | short-circuit evaluation of expressions and ternary operations are allowed, are not allowed / / 0 | 2'no-unused-expressions': [
    //   2,
    //   { allowShortCircuit: false, allowTernary: true}, //], // Short circuit is not allowed:'no-mixed-spaces-and-tabs'A: [2,false], // Forbid mixing tabs and Spaces'linebreak-style': [0, 'windows'], // Newline style'no-multiple-empty-lines': [1, {Max: 2}], // The maximum number of blank lines cannot exceed 2'no-extra-semi': 2, // Prohibit redundant colons'no-debugger': 2, // Disable debugger //'space-before-function-paren': [2, { anonymous: 'never', named: 'never'}, // Add a space after the function name //'space-before-function-paren': ['error'.'always'],
    // or
    'space-before-function-paren': [
      'error',
      {
        anonymous: 'always',
        named: 'always',
        asyncArrow: 'always'}].'eol-last': 0, // The file ends with a single newline // eqeqeq:true, // Must use congruent if yestrue, requires the use of === and! In all comparisons. == // eqnull:true, // If yestrue, == null is allowed'lines-around-comment': 0, // Note before/after a line'operator-linebreak'A: [2,'after'], // The operator is still at the end of the line'prefer-const': 0, // Quotes: [1,'single'], // The quote type ' '"" ' '
    'id-match': 0, // named detection'array-bracket-spacing'A: [2,'always'], // specifies that the elements of the array must be separated by Spaces (after,). The never argument cannot be preceded by Spaces. The always argument must be preceded by Spaces: quotes: [2,'single'], // All single quotes // The last comma of the array and object key-value pairs, never: no trailing comma, always: no trailing comma, // always-multiline: multi-line mode must contain a comma, single-line mode cannot contain a comma'comma-dangle'A: [2,'never'].'computed-property-spacing'A: [2,'never'], // Whether Spaces are required before [and] when using square brackets. Optional arguments never, always semi: [2,'never'], // the statement enforces the semicolon to end without a semicolon'eol-last': 2, // Force a newline at the end of the file'semi-spacing': [0, { before: false, after: true}, // Space before and after the semicolon'arrow-body-style': 0, // do not disallow arrow functions directlyreturnObject strict: 2, // Use strict mode'use-isnan': 2, // disable the use of NaN when comparing, only isNaN()'valid-typeof': 2, // Must use a valid typeof value'space-in-parens': [0, 'always'].'template-curly-spacing'A: [2,'always'].'array-bracket-spacing'A: [2,'always'].'object-curly-spacing'A: [2,'always'].'computed-property-spacing'A: [2,'always'].'no-multiple-empty-lines': [2, { max: 1, maxEOF: 0, maxBOF: 0 }],
    quotes: [1, 'single'.'avoid-escape'].'no-use-before-define': [2, { functions: false }],
    semi: [0, 'never'].'prefer-const': 1,
    'react/prefer-es6-class': 0.'react/jsx-filename-extension': 0.'react/jsx-curly-spacing'A: [2,'always'].'react/jsx-indent': [2, 2],
    'react/prop-types': [1].'react/no-array-index-key': [1].'class-methods-use-this': 'off'.'no-undef': [1].'no-case-declarations': [1].'no-return-assign': [1].'no-param-reassign': [1].'no-shadow': [1],
    camelcase: [1],
    'no-unused-vars': 'off'.'no-underscore-dangle': [0, 'always']}}Copy the code

Husky hook pre-commit configuration

The react configuration package. Json

 "husky": {
    "hooks": {
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"."pre-commit": "lint-staged", // pre-commit the hook before the commit"pre-add": "lint-staged"."pre-push": "lint-staged"}},"lint-staged": {// You can configure the scope of folders and file types here"src/**/*.{jsx,txs,ts,js,json,css,md}": [
      "prettier --write"", // Use prettier to format the prettier"eslint --fix"// Then use esLint to auto-fix"git add"// Execute git]}Copy the code

Vue configuration package. Json

"gitHooks": {
    "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"."pre-commit": "lint-staged"
  },
  "lint-staged": {
    "*.js": [
      "vue-cli-service lint"."git add"]."*.vue": [
      "vue-cli-service lint"."git add"]}Copy the code

“Lint-passage” (kiss) Husky will call the pre-commit hook before you commit, execute lint-passage, and format the code if it doesn’t conform to prettier. Eslint’s rules are then checked, and if there are any irregularities that cannot be automatically fixed, the commit is stopped. If both pass, the code is added to the stage and then committed.

* If you want to skip verification

You can skip the validation rule by using the –no-verify directive

git add . && git commit --no-verify -m "Code specification forced to submit tests"Copy the code

added

About front-end engineering packaging is inevitable for every developer. Frequent build releases online can be a waste of time, so how do you avoid duplication?

In fact, gitHooks can help us do this. For example, we do the following configuration:

"gitHooks": {... ."pre-push": "yarn run build && git add . && git commit -am 'prod build'"
  },
  "lint-staged": {... }Copy the code

This is a perfect solution to our concerns, of course, this method also has some drawbacks. Such as:

  1. Multiplayer development needs to deal with conflicts every build;
  2. Each push is accompanied by a build;
  3. Release releases find that static resources are not up to date (there are many ways to solve this problem, such as making a public interface to manually refresh our static resources every time a release goes live, etc.).

In this section, we have a brief introduction about the launch of build project, and we will popularize it in detail later. Please pay attention to it!

conclusion

Some people say that the front-end city lion is the strangest animal in the world. When submitting code, prettier is used for layout, but when deploying online, uglify is used to compress the code, even the mother doesn’t recognize it. The fact is, if the code we write is ugly, there is no need to use Uglify. Hopefully, by reading this, you’ve honed your Lint workflow to the limit, spent more time focusing on solving real problems, and become a truly effective engineer