ESLint started by telling me how I used Vue to validate code on team projects. I recently came across an old project, and one of the interesting things about this project was that the front and back end of the project were next to each other, and the back end would also modify the front end of the project, so the back end used IntelliJ IDEA to develop the front end of the project, The front end uses VSCode to develop the front end project. As a result, there are code specification issues, so this article has sorted out the front-end code validation and practices in the Vue project.

After reading this article, you can learn:

Write your own ESLint configuration; You will know the well-known JS code specifications in the industry, which will enable you to write more standard code; Vue-cli what it does when initializing a project that contains code validation; 1. What is Prettier? Why use it? How does it work with ESLint? What is EditorConfig? How to use it? How to use plug-ins in VSCode to assist code verification; How to ensure that code pushed to a remote repository is compliant with the specification; Read on and skip this section if you’re familiar with ESLint.

ESLint is an integrated code review and repair tool. Its core function is to configure rules to limit the validity and style of code.

Configuration parser and analytical parameters ESLint parser, early use is Esprima, behind based on Esprima v1.2.2 version launched a new parser Espree, and use it as a default parser.

In addition to using the parser that comes with ESLint, you can specify other parsers:

@babel/eslint-parser: makes Babel compatible with ESLint and supports some Babel syntax; @typescript-eslint/parser: With the deprecation of TSLint, typescript provides this parser for ESTree compatibility to enable esLint to support typescript; What are the principles for specifying a selector for a project?

If your project uses a relatively new ES syntax, such as ES2021 promise.any (), specify @babel/eslint-parser as the parser. If the project is based on TS, use @typescript-esLint /parser; If you are not familiar with the latest ES standard, check out this article: a well-summarized 30,000-word practical guide to ES6.

In addition to specifying the parser, you can also configure the parser parameter parserOption:

{
    // ESLint is the default parser, or you can specify something else
    parser: "espree".parserOption: {
        // Specify the version of ECMAScript to use, default 5
        ecmaVersion: 5.// Set to script (default) or module (if your code is an ECMAScript module)
        sourceType: "script".// This is an object that represents additional language features you want to use. All options default to false
        ecmafeatures: {
            // Whether the return statement is allowed in the global scope
            globalReturn: false.// Enable global strict mode (strict mode)
            impliedStrict: false.// Whether to enable JSX
            jsx: false./ / whether to enable support for experimental objectRest/spreadProperties
            experimentalObjectRestSpread: false}}}Copy the code

Env Specifies that different environments can provide default global variables for the corresponding environment. For example, in the Browser environment, you can use the window global variable; In the Node environment, you can use the Process global variable, etc.

There are a number of environments that can be configured in ESLint. Here is a complete list of the most common ones:

  • Browser: browser global variable;
  • Node.js global variables and scopes;
  • Es6: es6 in addition to the modules of the other features, at the same time will automatically set parserOptions. EcmaVersion parameters for 6; ES2017 is 7 and ES2021 is 12.
  • Es2017: parserOptions. EcmaVersion for 8;
  • Es2020: parserOptions ecmaVersion is 11;
  • Es2021: parserOptions. EcmaVersion to 12;

The configuration mode is as follows:

{
    env: {
        browser: true,
        node: true,
        es6: true,
        commonjs: true,
        mocha: true,
        jquery: true,
    }
}
Copy the code

Being able to specify multiple environments does not mean that the more environments you can configure, the better. The actual configuration depends on the current project environment.

Some of the core rules of Globals ESLint rely on knowledge of global variables available to your code at runtime. Because these can vary widely from environment to environment and change at run time, ESLint does not assume that global variables exist in your execution environment.

If you want to use these global variables, you can specify them with globals. For example, in react.eslintrc.js, spyOnDev, spyOnProd and other variables are attached to global as global variables:

{
    globals: {
        spyOnDev: true,
        spyOnProd: true,
    }
}
Copy the code

A special note is required for its value:

False, readable, and ReadOnly are equivalent, indicating that a variable can only be read but not written. True, writeable, and writable are equivalent, indicating that a variable can be read and written. Configuration extends Extends when configuring rules in a real project, it is too much effort for the team to negotiate the configuration one by one. The usual approach is to use the industry’s common use, follow the code specification; These specifications are then introduced through extends. Extends configuration accepts strings or arrays:

{ extends: ['eslint:recommended', 'plugin:vue/essential', 'eslint-config-standard', // can abbreviate 'standard' '@vue/prettier', './node_modules/coding-standard/.eslintrc-es6' ] }Copy the code

From the above configuration, you can see that extends supports one of the following configuration types

  • Eslint – beginning: is an official extension of ESLint;

  • Plugin: plugin type extension, e.g. Plugin :vue/essential;

  • Eslint-config: from the NPM package and can be used without the prefix eslint-config-, for example, as standard;

  • @ : extensions like eslint-config add a layer of scope on top of the NPM package;

  • A relative or absolute path to execute the configuration file;

  • What are some common and well-known extensions that extends can introduce

  • Eslint :recommended: built-in esLint recommended Rules, i.e. Rules that are checked in the list of ESLint Rules;

  • Eslint :all: All rules built into ESLint;

  • Eslint-config-standard: the JS specification for standard;

  • Eslint-config-prettier: Shuts off a rule that conflicts with ESLint and other extensions;

  • Eslint-config-airbnb-base: JS specification for AirBab;

  • Eslint-config-alloy: the product of Tencent AlloyTeam, you can configure the stack of your project very well, such as React, Vue (Vue 3.0 support), TypeScript, etc.

  • Use plugins

  • ESLint provides plugins for what to do

ESLint can define a lot of rules and introduce more rules through extends, but ultimately it just checks JS syntax. If you need to check template in Vue or JSX in React, there’s nothing you can do. So plugins were introduced to enhance ESLint’s checking capabilities and scope.

How to configure plug-ins

Eslint-related plugins can be named in one of two ways: without namespaces and with namespaces, for example:

  • Eslint-plugin – can omit this prefix;
  • @/;
{ plugins: ['jquery', // refers to eslint-plugin-jquery '@jquery/jquery', // refers to @jquery/eslint-plugin-jquery '@foobar', Foobar /eslint-plugin]}Copy the code

When you need to configure extends and Rules based on plug-ins, you need to add a reference to the plug-in, such as:

{
    plugins: [
        'jquery',   // eslint-plugin-jquery
        '@foo/foo', // @foo/eslint-plugin-foo
        '@bar,      // @bar/eslint-plugin
    ],
    extends: [
        'plugin:jquery/recommended',
        'plugin:@foo/foo/recommended',
        'plugin:@bar/recommended'
    ],
    rules: {
        'jquery/a-rule': 'error',
        '@foo/foo/some-rule': 'error',
        '@bar/another-rule': 'error'
    },
}
Copy the code

The above configuration comes from ESLint plugins

ESLint provides a large number of built-in rules. Here is a list of ESLint rules. You can also add more rules via plug-ins.

The verification specification of the rule has three error levels

Off or 0: disables the verification of the rule. Warn or 1: Enable the rule. If the rule is not met, a warning will be raised and the compilation process will not exit. Error or 2: enable the rule. If the rule is not met, an error will be thrown and the compilation process will exit. Generally, rules only need to be enabled or disabled. But there are rules that can pass attributes, such as:

{rules: {' quotes' : [' error ', 'single'], / / if not single quotes, then an error: 'one - var' [' error '{' var' : 'always', // each function scope allows only 1 var declaration 'let': 'never', // each block scope allows multiple lets to declare 'const': 'never', // allow multiple const declarations per block scope}]}}Copy the code

How do I know which rules can be configured for an extension and the specific restrictions for each rule? Here’s a quick link to a list of well-known and widely used rules in the industry:

  • ESLint :recommenmed ESLint :recommenmed ESLint: Recommenmed
  • Prettier rules
  • standard rules
  • airbnb rules
  • AlloyTeam vue rules

Priority of the rule

If the extends configuration is an array, it will eventually merge all rule items, and in case of a conflict, the latter overwrites the former. Rules configured separately through rules have a higher priority than extends; Others Set the current directory to root

ESLint checks configuration files for the following steps:

Look for.eslintrc.* and package.json in the same directory as the file you want to test. Then look in the parent directory until you reach the root directory of the file system. If you found root: true configuration in the previous two steps, stop looking for.eslintrc in the parent directory; If no, go back to the default configuration in the user home directory ~/.eslintrc. It is common practice to put the ESLint configuration files in the root directory of the project, so to avoid looking up configuration files in the parent directory for ESLint validation, add root: true to the configuration files.

{
    root: true,
}
Copy the code

Adding Shared Data

ESLint supports adding shared Settings to configuration files. You can add Settings objects to configuration files, which will provide for each rule that will be executed. This would be useful if you wanted to add custom rules and make them accessible to the same information, and easy to configure:

{
    settings: {
        sharedData: 'Hello'
    }, 
}
Copy the code

For details, see the eslintrc configuration file

Set new check rules for individual files

For example, Webpack contains some runtime JS files that only run in the browser, so differentiated configuration is needed for these files:

overrides: [
    {
        files: ["lib/**/*.runtime.js"."hot/*.js"].env: {
            es6: false.browser: true
        },
            globals: {
            Promise: false
        },
        parserOptions: {
            ecmaVersion: 5}}]Copy the code

The above configuration comes from webpack.eslintrc.js

The above details the various configuration items for ESLint and instructions on how to configure them differently for Vue projects.

Now we know how to configure, but do you know where these configurations go?

Configuration Modes ESLint supports three configuration modes:

Command line: not recommended, not introduced; Notes in single file: not recommended, not introduced; Configuration file: The configuration file can be of several types, such as.js,. Yml, and json. .eslintrc.js is recommended; The following command generates a configuration file:

Install eslint

npm i eslint -D
Copy the code

Initialize a configuration file

npx eslint --init
Copy the code

Finally, an.eslintrc.js file is generated in the current directory. I won’t post the code here for reference.

We know that you can write the configuration to a single configuration file, but do you know how to trigger the configuration file validation rules?

Verifying a single file

// verify a.js and b.js NPX eslint a.js b.js // verify SRC and scripts directory NPX eslint SRC scriptsCopy the code

In general, ESLint can only validate JS files. For example, to validate.vue files, it is not enough to simply configure the vue plugin and vue-eslint-parser. You also need to make esLint find.vue files when looking for files.

You can specify which files to verify with –ext:

npx eslint --ext .js,.jsx,.vue src
Copy the code

Rules that mark a wrench 🔧 pattern in the rules list item indicate that the rule can be fixed automatically using the ESLint tool. How do you fix it automatically? Pass –fix. For example, the Semi rule in ESLint Rules has a wrench pattern.

For the following a.js code:

const num = 12
Copy the code

When ‘semi’: [2, ‘always’] is configured in the configuration file, run the following command:

npx eslint --fix a.js
Copy the code

The validation passes directly and the code is automatically fixed with a semicolon at the end of the code.

Json validation commands are long and difficult to remember, so it is customary to write these names directly to package.json:

{
    "scripts": {
        "lint": "npx eslint --ext .js,.jsx,.vue src",
        "lint:fix": "npx eslint --fix --ext .js,.jsx,.vue src",
    }
}
Copy the code

Some common JS files, test scripts, or files in specific directories do not require validation, so this can be configured in the project root directory by creating an.eslintignore file that tells ESLint to ignore them during validation:

public/
src/main.js
Copy the code

ESLint always ignores files in /node_modules/ and /bower_components/ except for files or directories specified in.eslintignore; So for some rules that cannot be resolved at the moment, but if we are in a hurry to pack up and go live, we can ignore them temporarily with the.eslintignore file without affecting the operation.

Almost all configuration parameters and verification methods of ESLint are described in detail in the Vue project practice above, but if you want to land in the project, just rely on the above knowledge is not enough. The following details how to implement code validation in Vue.

In terms of how to implement code verification in Vue, there are generally two situations:

For an empty VUE project, if you want to access code for verification, the final verification core configuration is the same in both cases, but the package installed at the beginning is different. Let’s take a look at code validation for vue-CLI configuration to see what it does. By looking at the packages it installs and what those packages do, we’ll know how to configure code validation in empty projects.

If your project was originally created using vue-CLI, you will be given the option when creating it

Whether esLint is supported; Whether to enable save verification; Whether to enable pre-submission verification; If both are enabled, the following packages will be installed:

Eslint: a basic package for code validation that provides many built-in Rules, such as ESLint :recommended, which is often introduced as a JS checking specification for a project; esLint :recommended. Babel-eslint: A wrapper around the Babel parser to make it compatible with ESLint; Lint-staged: See the pre-commit section below; @vue/cli-plugin-eslint eslint-plugin-vue The following sections will focus on @vue/cli-plugin-eslint and eslint-plugin-vue.

@vue/ cli-plugin-esLint this package does two things:

The first thing to do

Json register a command to package.json:

{
    "scripts": {
        "lint": "vue-cli-service lint"}}Copy the code

After executing this command, it checks and fixes some of the problems that can be fixed. The default files to look for are all.js,.jsx,.vue files in the SRC and tests directories, as well as all js files in the project root directory (for example,.eslintrc.js is also checked).

Of course you can also customize the incoming parameters and validation files:

vue-cli-service lint [options] [...files]
Copy the code

The following parameters are supported:

–no-fix: errors and warnings will not be fixed; –max-errors [limit] : specifies the maximum number of errors that cause NPM errors. The second thing

– Added lintOnSave, which is enabled by default. If you want to disable this function, you can configure it in vue.config.js. Traditionally, only the code save verification function in the development environment is enabled:

module.exports = {
    lintOnSave: process.env.NODE_ENV === 'development',}Copy the code

LintOnSave Parameters:

  • True or warning: If save verification is enabled, errors of the errors level will be displayed as warning on the terminal. By default, WARNING will not cause compilation failures;
  • False: save verification is disabled.
  • Error: If save verification is enabled, errors of the errors level are displayed as errors on the terminal. As a result, compilation fails and the browser page turns black, indicating Failed to compile.
  • eslint-plugin-vue
  • Eslint-plugin-vue is a plugin that validates.vue files.
  • It provides these extensions for this plug-in
  • The plugin: vue/base: the base
  • Plugin :vue/essential: prevent error (for vue 2.x)
  • Plugin :vue/recommended: minimizes arbitrary choice and cognitive overhead (for Vue 2.x);
  • Plugin :vue/strongly recommended: improve readability (for vue 2.x);
  • Plugin :vue/vue3-essential: (for vue 3.x)
  • Plugin: Vue /vue3- Strongly – Recommended (vue 3.x)
  • Plugin :vue/vue3-recommended: (for Vue 3.x)
  • List of extended rules: Vue rules

When you see so many extensions, you don’t know which one to choose

Code standards, principles or by the respective teams to work out a set of rules for everyone. However, if you’re using Vue2, I can recommend two extends configurations:

{
    // Configuration on the Vue official example
   extends: ['eslint:recommended'.'plugin:vue/recommended'].// Or use AlloyTeam
   extends: ['alloy'.'alloy/vue']}Copy the code

Configure the parser corresponding to the plug-in

For Vue 2.x projects, template validation will still fail after the eslint-plugin-vue plugin and extends are configured, because either esLint’s default parser, Espree or babel-esLint, can only parse JS. Unable to parse the contents of template.

Vue-eslint-parser parses only template content, but not JS, so you need to configure the parser as follows:

{
    parser: 'vue-eslint-parser'.parseOptions: {
        parser: 'babel-eslint'.ecmaVersion: 12.sourceType: 'module'
    },
    extends: [
        'eslint:recommended'.'plugin:vue/recommended'].plugins: ['vue']}Copy the code

Refer to the eslint-plugin-vue FAQ

  • Let Prettier control code style
  • Prettier does Prettier have to ask?
  • 1. What is Prettier?
  • Why does ESLint need Prettier? What’s the difference between them?
  • How do I configure Prettier?
  • How does Prettier work with ESLint?
  • What is Prettier
  • In its own words: I’m a self-righteous code formatter, and I support many file types, such as:
  • JavaScript (including features in the experiment)
  • JSX
  • Vue
  • TypeScript
  • CSS, Less, and SCSS
  • HTML
  • JSON
  • Markdown

And there are other types of files.

Prettier vs. ESLint We know that ESLint validates code and provides two main types of rules:

  • Review formatting rules
  • Rules for checking code quality
  • After all, ESLint has rules that restrict code specification, but those rules are limited and, more importantly, they don’t focus on code style, so ESLint alone can’t completely unify code style.

That’s where Prettier comes in because it formats code regardless of its quality.

Prettier: When it comes to code style, I’m pretty tight.

How to configure Prettier initialization:

The installation package

npm i prettier -D

New. Prettierrc. Js

echo module.exports = {} > .prettierrc.js

New. Prettierignore

echo > .prettierignore
Copy the code

Prettier Options Prettier options is a relatively small number of parameters where there are only 21 Prettier options

2, All parameters have default values, that is, even if you don’t configure.prettierrc.js, when you format code using Prettier, it always goes to default values. For an individual parameter, you can configure the desired value in.prettierrc.js if you do not want to use the default.

Here is a description of the parameters used in the project:

module.exports = {
    printWidth: 80.// (default) Wrap a single line of code beyond 80 characters
    tabWidth: 2.// (default) A TAB key is indent equal to 2 Spaces
    useTabs: true.// Indent lines using the TAB key instead of Spaces
    semi: false.// (default) semicolon at the end of the statement
    singleQuote: true.// Use single quotes
    quoteProps: 'as-needed'.// (default) double quotes are used only when necessary
    jsxSingleQuote: true.// Use single quotes in JSX
    trailingComma: 'all'.// Do not add a comma at the end of the last line of a multiline comma-separated syntax
    bracketSpacing: true.// (default) Add a space between the parentheses and the object text
    jsxBracketSameLine: true.// Place the > symbol on the last line of the multi-line JSX element
    arrowParens: 'avoid'.// Omit parentheses when the arrow function has only one argument
    vueIndentScriptAndStyle: false.// (default) For.vue files, do not indent 
    embeddedLanguageFormatting: 'off'.It is not allowed to format embedded code blocks, such as those in markdown files
};
Copy the code

Read more: You might want to know more about the Trailing commas.

You can then format the code with a command:

All files in the current directory and subdirectories will be formatted

npx prettier --write .
Copy the code

Check whether a file has been formatted

npx prettier --check src/main.js
Copy the code

If there are files that do not want Prettier formatted, you can write them to. Prettier Ignore:

build/
package.json
public/
test/*.*
Copy the code

Prettier Prettier and ESLint Prettier is Prettier when working with ESLint, where Prettier is used, and what to do when working with ESLint

Working with ESLint requires the plugin eslint-plugin-prettier:

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

Configuration:

{
    plugins: ['prettier'].rules: {
        'prettier/prettier': 'error'}}Copy the code

Prettier this plugin works by calling Prettier to format your code, and then marking incompatibility with ‘Prettier/Prettier ‘: ‘error’ This rule will mark the place with an error, which can then be fixed by ESLint’s –fix auto-fix feature.

What if there’s a conflict?

As we already know, ESLint also does some restrictions on code style, while Prettier is just code style, so there are some problems when using them together. For some rules, the two sides may have the problem of inconsistent code format after verification.

So what happens when Prettier and ESLint conflict?

Prettier is easy, just use eslint-config-prettier. The idea for resolving conflicts is to introduce the extension provided by this package at the end of the extends extends, according to the precedence that rules takes effect, so it overwrites the previously conflicting rules, for example:

{
    extends: [
        'eslint:recommended'.'prettier'.// It must be played last],}Copy the code

In addition to overwriting rules that conflict with ESLint, eslint-config-Prettier also overwrites rules from plugins (only partially listed) :

Eslint-plugin-standard eslint-plugin-vue What override rule does eslint-config-prettier provide? Look directly at the list: eslint-config-prettier Rules

If you want to override rules for certain plug-ins, you need to introduce extensions for the plug-ins, such as:

{
    extends: [
        'standard'.'plugin:vue/recommended'.'prettier/standard'./ / cover eslint - config - stanard
        'prettier/vue'./ / cover eslint - plugin - vue],}Copy the code

Tip: After eslint-config-prettier 8.0.0, extends no longer needs to include an extension for a separate plug-in to cover conflicts, just ‘prettier’.

Where eslint-plugin-prettier and eslint-config-prettier are used together:

{
    extends: ['plugin:prettier/recommended'],}Copy the code

It is equivalent to the following configuration:

{
    extends: ['prettier'].// eslint-config-prettier, used to override conflicting rules
    plugins: ['prettier'].// Register the eslint-plugin-prettier plugin
    rules: {
        'prettier/prettier': 'error'.'arrow-body-style': 'off'.'prefer-arrow-callback': 'off'}}Copy the code

So ESLint and Prettier in a Vue 2 project would look like this:

{
    parser: 'vue-eslint-parser'.parseOptions: {
        parser: 'babel-eslint'.ecmaVersion: 12.sourceType: 'module'
    },
    extends: [
        'eslint:recommended'.'plugin:vue/recommended'.'plugin:prettier/recommended'.// Add this line to the previous Vue configuration].plugins: ['vue']}Copy the code

The extends configuration in the.eslintrc.js configuration file would look something like this if your project was initialized using jue-CLI and esLint + prettier was used:

{
    extends: [
        'plugin:vue/essential'.'eslint:recommended'.'@vue/prettier']}Copy the code

The last extension is @vue/prettier, which corresponds to @vue/eslint-config-prettier. Let’s look at the contents of index.js below the @vue/eslint-config-prettier package:

{
    plugins: ['prettier'].extends: [
        require.resolve('eslint-config-prettier'),
        require.resolve('eslint-config-prettier/vue')].rules: {
        'prettier/prettier': 'warn'}}Copy the code

This is similar to what we configured above, Eslint-config-prettier /vue was introduced because the @vue/eslint-config-prettier package relies on eslint-config-prettier ^6.0.0, Therefore, when dealing with conflicts, you need to specify the extension that matches the corresponding type of plug-in.

Let EditorConfig help with multi-editor development what is EditorConfig? It can simply format multiple types of single files, and it provides few configuration parameters:

Tell the EditorConfig plugin that this is the root file and you don’t need to go any further

root = true

Match all files

[*]

Set character set

charset = utf-8

Indent style, optional space, TAB

indent_style = tab

The number of Spaces indent when indent_style = TAB will use tab_width

Otherwise indent_size is used

indent_size = 2 tab_width = 2

The value can be LF, CR, or CRLF

end_of_line = lf

Insert a new line at the end of the file

insert_final_newline = true

Deletes the Spaces before and after a line

trim_trailing_whitespace = true

Matches files ending in MD

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
Copy the code

Although it provides few configuration parameters for formatting, just three, indenting style, whether to insert a new line at the end of the file, and whether to remove Spaces before and after a line. But it is still very necessary for three reasons:

Ability to maintain consistent code style across different editors and ides; With plug-in open file automatic formatting, very convenient to support a lot of formatted file types; To make the above configuration work, you need to install the EditorConfig for VSCode plugin in VSCode.

The key to the

EditorConfig and Prettier duplicate configurations. For example, EditorConfig and Prettier both provide indentation, so avoid them or set them the same.

ESLint is supported in VSCode

The previous configuration requires executing commands to check and repair the code, which is still quite inconvenient. What if I want to check the code after editing or saving it? You can install the ESLint plugin directly in the IDE, since I’m using VSCode, I’ll only cover the configuration in VSCode here.

To use it, you need to install the ESLint extension into VSCode, which I won’t go through here. After the installation is complete, you need to write the configuration in the Settings:

Find a gear âš™ icon in the lower left corner of VSCode, click and select Settings, this time opens the Settings panel; Find the open Settings (json) icon in the upper right corner of VSCode and click on it to open the settings.json file. Then paste in the following configuration;

{
    "eslint.alwaysShowStatus": true.// always display ESLint status in VSCode
    "eslint.quiet": true.// Ignore the error warning
    "editor.codeActionsOnSave": {     // Save using ESLint fixes fixes errors
        "source.fixAll": true."source.fixAll.eslint": true}}Copy the code

Configuration instructions, starting with ESLint version 2.0.4:

Eslint. validate does not need to specify the type of file to validate,.vue files are already automatically supported; Editor. codeActionsOnSave Enables automatic saving and repair; ESLint validates code in real time every time you edit it, and will fix it automatically when you save it. For code that does not fix automatically, you need to manually modify it. If you do not want to modify it, you can configure rules to disable this rule.

In fact, when the team is developing, it is best to write a file for VSCode configuration along with the project, and submit it to the remote repository, so that the project members are sure to use this configuration. For example, you can create.vscode/settings.json in the project root directory and write the above configuration.

ESLint automatically fixes fixes errors that can be fixed and formats code using Prettier, but there are bugs that cannot be fixed during actual development and developers forget to modify them. If you commit code to a remote repository at this point, you’re committing bad code.

So how do you stop submitting bad code? You can do this by configuring the pre-commit hooks of Git hooks. Husky and Lint-staged packages were primarily used. Husky is used to configure Git hooks, while Lint-passage is used to manipulate passage files taken from it, such as NPX ESLint –fix for code validation.

The specific operation steps are as follows:

1. Run the following command:

npx mrm lint-staged
Copy the code

Lint-passage and Husky are automatically installed and lint-passage is written in package.json.

Note: MRM is an automated tool that will install and configure Husky and Lint-staged from code quality tools in package.json dependencies, so be sure to install and configure all code quality tools, such as Prettier and ESlint, before doing so.

Lint-staged files can be modified to support validation of.vue files if package.json has been written successfully above:

{
    "lint-staged": {
        "*.{js,vue}": "eslint --cache --fix"
    }
}
Copy the code

Start Git hooks

npx husky install
Copy the code

After the above command, the v6 version of Husky creates a new.husky directory in the project root. If it is v4, it will be written to package.json.

Create a pre-commit hook

npx husky add .husky/pre-commit "npx lint-staged"
Copy the code

At this point, the automatic code verification and repair before git commit is complete. Then you can try to modify the file and submit it.

conclusion

This is a long article that covers a lot of code validation, so let’s sort it out.

ESLint first uses ESLint for code validation. Its built-in Ruels provide two types of validation: error verification and format verification. ESLint’s core job is to verify and fix bad code, not much for formatting rules.

Prettier is used when you want to format code more subtly, because Prettier only controls style. But when ESLint and Prettier are used together, there might be a rule conflict because they both manipulate styles. The extension eslint-config-prettier shuts off the conflicting rule. This extension turns off conflicts not only with ESLint built-in rules, but also with extension rules referenced in real projects, such as Vue, React, TypeScript, and Flow.

Prettier when ESLint is combined with Prettier, where ESLint checks code for errors while Prettier checks code style, there are two tasks requiring two commands. But eslint-plugin-prettier makes it easy to combine them. Eslint automatically checks code for errors when it needs to be corrected, as long as VSCode follows the eslint plugin, ESLint calls Prettier’s ability to check code style when it needs to do so.

Article source: juejin.cn/post/697422…