Configuration instructions for eslint+prettier+husky

Keywords: Javascript Front-end Vue.js

One, eslint

Eslint specifies code that is syntactically biased. This article describes the eslint+prettier+husky configuration project code specification as a basic vue project. To better describe this article, I restored the default settings for vscode (i.e. no eslint,prettier plug-ins are installed, and no configuration is available in settings)

๐Ÿš€ 1, create a new empty vue2.x project (eslint is not installed)

vue create eslint-test

๐Ÿš€ 2, install selint separately

npm install eslint --save-dev
npx eslint --init

Generate.eslintrc.js file:

module.exports = {
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": [
        "eslint:recommended",//Inherit the (hooked) rule item recommended in Eslink http://eslint.cn/docs/rules/
        "plugin:vue/essential"// This item is used to configure the vue.js style
    ],
    "parserOptions": {
        "ecmaVersion": 13,
        "sourceType": "module"
    },
    "plugins": [
        "vue"
    ],
    "rules": {
    }
};

๐Ÿš€ 3, see this recommended default rule

The rules here, written later, will override the previous rules, and the rules in rules will override this last, so our custom rules are written in rules to override the previous rules and take effect.

"extends": [
    "eslint:recommended",//Inherit the (hooked) rule item recommended in Eslink http://eslint.cn/docs/rules/
    "plugin:vue/essential"// This item is used to configure the vue.js style https://eslint.vuejs.org/rules
],

quotes - Rules - ESLint Chinese

Available rules | eslint-plugin-vue (vuejs.org)

How does this default rule work? For example, if we click on the link, we can see that this no-debugger is a check-mark (i.e.'eslint:recommended') rule, then we write a debugger in the project, and then the command line runs the command to check eslint, which will result in an error.

Project Root Execution:

npx eslint --ext .vue src/
Equivalent to:./node_modules/.bin/eslint --ext .vue src/
--ext:You can specify in the specified directory/file
.vue: vue file
src/: stay src Match under Catalog

๐Ÿš€ 4, Custom Rules

Eslint comes with a number of check rules whose values are as follows:

  • off | 0: Represents a closing rule.
  • warn | 1: Indicates that the rule is converted to a warning.
  • error | 2: Indicates that the rule is converted to an error.

Common rules rules can be found on the official website: List of available rules - ESLint Chinese

// 'semi': [2,'always'], //statement forces semicolon end
// 'quotes': [2,'double'], //quote type''
//"no-alert": 0, //Prohibit use of alert
//"no-console": 2, //Prohibit console use
//"no-const-assign": 2, //Prohibit modifying variables declared by const
//"no-debugger": 2, //Prohibit use of debugger
//"no-duplicate-case": 2,//switch case label cannot be repeated
//"no-extra-semi": 2, //Prohibit extra colons
//"no-multi-spaces": 1, //Cannot use extra spaces

When we run the check after a semicolon is required at the end of a custom configuration like this, the corresponding error will be reported in the project:

๐Ÿš€ 5, Configure check command line in package.json

In the previous section, we manually entered the command line to check if the code conforms to the eslint specification, so that each check would be entered again. What if someone can't remember the command? This script can then be written to death in package.json's script:

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

Thus, the project root directory runs npm run lint, which actually runs:

npx eslint --ext .js --ext .jsx --ext .vue src/

This enables code inspection:

๐Ÿš€ 6, eslint plug-in auto-check specification

Do you want NPM run link to check if it meets the specification every time you finish writing a code? That's too much trouble. So there are eslint plug-ins, here I use vscode, open the plug-in market, search for eslint, install it:

What will happen after installation? It automatically checks your code for symbolic specifications, identifies in the editor where nonconformances occur, and lists the issues at the bottom end:

๐Ÿš€ 7, Configure the auto-repair command line in package.json

For example, we have written a lot of these bug s above, one by one manual repair, which is too troublesome. eslint provides a command line for fixing code that doesn't conform to the specification, but this fix isn't everything, the website says, there's this (wrench) ๐Ÿ”ง Icons correspond to rules that can be fixed.

As you can see, the debugger rule should not be repairable, while the semicolon rule can be repaired automatically.

Specific command lines are also set in package.json:

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

Execute this npm run lint-fix in the root directory:

You can see that the semicolon error has been fixed, and debugger can't fix it automatically but can only fix it manually.

๐Ÿš€ 8, configure setting s in vscode to automatically repair each time code is saved

Ignoring debugger, which can only be repaired manually, in actual writing code, we often encounter semicolons, single and double quotation marks, which can be automatically repaired. So, do we still need to hit npm run lint-fix manually each time? That's also inefficient. Now with vscode's eslint plug-in, we can write the code and see if it meets the specification. However, what we want to achieve is that every time we finish writing the code, it will be repaired automatically when we press ctrl+s to save.

Fortunately, vscode's setting.json helps us do this:

stay vscode Middle Press Shortcut ctrl+shift+p๏ผŒinput setting,open setting.json

Increase this configuration (if vscode is not restarted):

 //Follow the rules of the eslint file when configuring save to process the code
"editor.codeActionsOnSave": {
    "source.fixAll": true,
    "eslint.autoFixOnSave" : true,
  },

You can see that as soon as I press Save, I automatically fix the problem with the sign.

๐Ÿš€ 9, Configure eslintignore

Some files, which we don't want to be governed by eslint, can be created in the root directory. eslintignore files, just throw in the files or directories that you want to be free:

.eslintrc.js
.prettierrc.js
babel.config.js
vetur.config.js
/node_modules/

๐Ÿš€ 10, Summary

Reflect on a few questions:

  • Why do we need eslint?
	Because everyone's code habits are different, each developer needs to collaborate with others or project needs to be handed over to the next generation of developers. Maintaining a unified code specification can greatly improve efficiency and reduce the cost of communicating and understanding code.
  • Now that we have the eslint plug-in for vscode to help us automatically check and fix code, why do we need to configure the eslint command line in pakage.json?
	because vscode It's an editor on our own computer, and we can't guarantee that another person will get our code as well vscode (Maybe he uses Notepad?). Even if he uses it vscode,We can't guarantee he installed it either eslint Plug-in unit.
	 ๏ผŒHe can use it pakage.json To check and repair the code. Because installation is definitely required in the project eslint Dependency, there must be something we configure.eslintrc.js Rule file, which still guarantees a uniform specification of the code.

Two, prettier

๐Ÿ‘บ 1. The role of prettier

We have configured eslint above, which specifies a syntactically biased style of code. For example, console s cannot be used. Arrow function parameters must be enclosed in parentheses.

Sometimes in a project, we write code to delete or change, or personal code habits, such code may appear:

<script>
	import HelloWorld from './components/HelloWorld.vue';
        export default {
                name: 'App',
        components: {
    HelloWorld
  }
};
</script>

When typesetting is messy or when writing html, code typesetting issues such as line breaks or no line breaks are too long, requiring prettier to be standardized.

That is, the prettier specification is that the code is biased toward a typesetting style.

๐Ÿ‘บ 2, install prettier

npm install --save-dev --save-exact prettier

๐Ÿ‘บ 3. Repair formatting using the command line

npx prettier --write src/

As you can see, the code I had deliberately scribed became neat.

๐Ÿ‘บ 4. Configure custom prettier rules

You need to create a new file in the root directory. prettierrc.js (module.export is required) or. prettierrc (only json format is required):

//The rules here are for reference, and most of them are actually default values, which can be overridden according to your personal habits
module.exports = {
    printWidth: 80, //Single Line Length
    tabWidth: 2, //Indentation Length
    useTabs: false, //Use spaces instead of tab indentation
    semi: false, //Use semicolons at the end of a sentence
    singleQuote: false, //single quotes
    arrowParens: "avoid",//Use parentheses around single-parameter arrow function parameters - eg: (x) => xavoid: omit parentheses
    bracketSpacing: true,//Add space-eg before and after the object: {foo: bar}
    insertPragma: false,//Label the top of the file that has been formatted by preitter
    jsxBracketSameLine: false,//'>'wrap placement for multi-attribute html tags
    rangeStart: 0,
    requirePragma: false,//Format without Top Comment
    trailingComma: "none",//Print trailing commas as as many lines as possible
    useTabs: false//Use spaces instead of tab indentation
  };

To test for validity, I deliberately wrote false with a semicolon at the end of a sentence (eslint needs a semicolon above). Executing npx prettier --write src/, you can see that the semicolon was cancelled, but the eslink rule was not met and an error was reported:

Conflicting issues Later on, this just means that the.prettierrc.js we configured is valid.

๐Ÿ‘บ 5, prettier plugin save code Auto-repair

Similarly, it's not possible to run npx prettier --write src/ to beautify code every line of code, so you need to install the prettier plug-in again.

Then ctrl+shift+p opens the setting.json file of vscode and adds the following configuration:

 //prettier can format many formats, so you need to configure them here
 "[html]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[css]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[less]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[vue]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[jsonc]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  //This setting enables Default Formatting when ctrl+s, here is prettier
  "editor.formatOnSave": true

Press Save Code at this time and you will find that it is still a bug to report eslint:

This is because the rules of eslint conflict with prettier when we save. Auto-repair of eslint is performed first, and the semicolon is added. Then prettier's repair is performed, and the semicolon is removed, which results in a flicker and an eslink error in the end. This mainly reflects prettier's ability to automatically fix conflicts when saving code. Conflict issues are still mentioned later.

๐Ÿ‘บ 6, allow the compiler to report prettier errors

So far, for eslint, we haven't been able to see where it doesn't conform to the rules, but just standardize the style of the code through automatic fixes. Now let's imagine, like eslint, that as soon as the code is written, if it doesn't, a red wave line will appear indicating where the problem is.

How can this be achieved? You can use eslint's error report to inject prettier into eslint as a plug-in to eslint, allowing eslint to report this error (in fact, vscode's eslint implementation)

Installation Dependency:

npm i -D eslint-plugin-prettier

Then add this configuration to the.eslintrc.js configuration file, which means that prettier errors are reported using eslint:

// .eslintrc.js
{
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}

After setting this up, I deliberately messed up the layout of the code:

Notice that the editor has been able to report both eslint and prettier errors.

Save the code and it will be automatically repaired except for the conflicting parts.

Now you can start to resolve the conflict between the two guys.

๐Ÿ‘บ 7. Resolve conflicts between eslint and prettier

Let's start with one thing. In fact, the conflict I've repeatedly said above. It's not really a conflict between eslint and prettier. Because of the conflict above, eslint's rules are set in.eslintrc.js's rules and prettier's in prettierrc.js, both of which are set by our developers themselves! It is clear that the front-end programmer is foolish and trips the editor! (So don't beat me, I'm still young and haven't married yet...)

By explaining the cause of the conflict, I can understand why I said so.

First, we installed eslint.

To verify the code, this eslint must have a default code specification.

As mentioned in Chapter 1, Section 3 above

"extends": [
    "eslint:recommended",//Inherit the (hooked) rule item recommended in Eslink http://eslint.cn/docs/rules/
    "plugin:vue/essential"// This item is used to configure the vue.js style
],

Here, eslint:recommended is the default rule, but sometimes we don't use it. Other mature rule scenarios such as the Airbnb specification will be used. For example, here I've added plugin:vue/essential as a specification for Vue files.

One more thing to emphasize here is that the rules in this extends array will override the previous ones, that is, the vue/essential will override the duplicate parts in recommended.

And the rules here are introduced by the installation dependency and stored in node_ The files in the modules folder are not allowed to change in order to keep other developers'code consistent.

So when it comes to conflicts between eslint and prettier, it's really about conflicts that rely on the introduced rules and prettier!

Rather than conflict between rules in eslint s you configure and prettier you configure.

To prove what I said, I went to node_modules/eslint/conf/eslint-recommended.js Add an eslint rule: (The rule set in this file is the checked part of the official website, quotes are not in the default rule, so I add one manually for better understanding)

Now this is the configuration in eslint, and I've turned off the custom configuration, which is the case in prettier. That is, the eslint default configuration requires double quotation marks, and the prettier setting requires single quotation marks, which conflict:

Now I press ctrl+s again to save the code, and you can see that the two are in conflict. (The modification does not take effect and vscode needs to be restarted):

Install the conflict resolution dependencies described online:

npm i -D eslint-config-prettier

Add the rules set by prettier to the extends array:

  extends: [
    'eslint:recommended', //Inherit the (hooked) rule item recommended in Eslink http://eslint.cn/docs/rules/
    'plugin:vue/essential', // This item is used to configure the vue.js style
    'prettier',//Add the rule set in prettier to override the rule set above. This will not conflict with the above rules
  ],

This invalidates all eslint rules before it that may conflict with prettier rules and uses prettier rules for code checking.

Then, in the project ctrl+s error code, you can see that the error disappeared and became a single quotation mark set by prettier:

This is the true way to resolve conflicts.

Next, what about conflicts in rules? It takes precedence over rules in extends, where conflicting rules have been invalidated by prettier, and you redefine them in rules, which in turn conflicts with prettier.

That is, resolving conflicts above will only resolve conflicts in extends. Conflicts in rules will not be resolved!

So how should we resolve this conflict?

The first option is to configure the rules you want to publish as npm packages and then introduce them into this extends array.

The second option is to keep the configuration in relus consistent with that in prettier.

๐Ÿ‘บ 8. Enable code formatting for projects without prettier installed

Sometimes our project does not configure prettier, and we want to beautify the code when it is saved in vscode. You can open set.json to configure prettier rules in ctrl+shift+p:

 /*  prettier Configuration */
  "prettier.printWidth": 80, // Line Break Over Maximum
  "prettier.tabWidth": 2, // Indent bytes
  "prettier.useTabs": false, // Add semicolon at end of sentence
  "prettier.singleQuote": false, // Use single quotation marks instead of double quotation marks
  "prettier.proseWrap": "preserve", //  (x) => {} Whether parentheses are required when the arrow function parameter is only one. avoid: omit parentheses
  "prettier.bracketSpacing": true, // Add a space'{foo: bar}'between the array brackets and the text for the object
  "prettier.endOfLine": "auto", // Ends with \n \r \nr Auto
  "prettier.eslintIntegration": false, //Do not let prettier use eslint's code format for validation
  "prettier.htmlWhitespaceSensitivity": "ignore",
  "prettier.ignorePath": ".prettierignore", // Fill in the project's.prettierignore file without prettier formatting
  "prettier.jsxBracketSameLine": false, // Put'>'on a separate line in jsx
  "prettier.jsxSingleQuote": false, // Use single quotation marks instead of double quotation marks in jsx
  "prettier.parser": "babylon", // Formatted parser, babylon by default
  "prettier.requireConfig": false, // Require a 'prettierconfig' to format prettier
  "prettier.stylelintIntegration": false, //Do not let prettier use stylelint's code format for validation
  "prettier.trailingComma": "none", // Is a comma added after the last element of an object or array (a trailing comma in ES5)
  "prettier.tslintIntegration": false,
  "prettier.arrowParens": "avoid"

๐Ÿ‘บ 9, Summary

Reflective questions:

  • Now that the pettier is set in vscode (point 8 above), you are ready to format your code, and you need to install a prettier dependency to configure the format.
Reasons and eslint In the same way, vscode Configured in, others may not use vscode๏ผŒPerhaps installed vscode,But not in setting.json Set specifications in. And item read prettier Specification has a priority if found in the root directory.prettier Files are not searched setting.json Rule in. Only found.prettier When filing, we configure the setting.json The rules in will take effect.

Third, eslint validation when submitting code

๐Ÿ˜ˆ1๏ผŒhusky

To ensure that the GIT code submitted each time is correct, we can use eslint with git hook to validate the eslint specification when making git commit

If eslint validation fails, it cannot be submitted.

We need to install a hook tool for git - husky (I just started installing the latest version and found it doesn't work until I roll back)

npm install husky@4.3.8 --save-dev

Then add the configuration in package.json:

"husky": {
    "hooks": {
      "pre-commit": "echo 'husky' && npm run lint"
    }
  }

This means to execute the command in pre-commit before git commit: we output husky here and execute npm run lint (the command we added to verify eslink in Chapter 1, Point 5 above)

If the eslint validation passes, a commit operation will occur, otherwise an eslint error will be reported.

The effective flag is that under the project's.git/hooks directory, a bunch of files will be generated, originally only files like pre-commit.sample, which will be added when the husky installation is complete.

Run the git commit command again and the code will be checked.

๐Ÿ˜ˆ2๏ผŒlint-staged

If this is more than a new project, it will meet the requirements, but if the project you get is an old one, someone else has developed it for a long time. At this time, if you add the eslint rule and check it globally, you will find a lot of error messages. This panic. Modifications may cause other problems.

To solve this problem, we need to introduce lint-stage

The purpose of lint-stage is to eslint code specification validation only for the code in the git add cache. This avoids the problem of global checking. If you modify the code above, you submit whatever code you have, and the rest of the code is not checked with eslint.

npm install --save-dev lint-staged

Add in package.json:

"lint-staged": {
    "src/**/*.{css๏ผŒscss,less}": [
      "npm run lint",
      "git commit"
    ],
    "src/**/*.{js,vue}": [
      "npm run lint",
      "git commit"
    ]
  }

Posted by Tomz on Tue, 23 Nov 2021 10:03:06 -0800