ESLint introduction

We know that it’s more efficient and rational to use a tool to validate project code these days, in this case ESLint.

It is currently the most popular javascrit Lint tool designed to monitor the quality of javascript code. ESLint makes it easy to unify the coding styles of different developers. Such as indentation, line breaks, semicolons and Spaces.

Not only that, ESLint can also help us find code that doesn’t make sense, such as when we define a variable that’s never used, or when we declare a variable after it’s used. Or we tend to choose the symbol equals equals when we make comparisons. And so on and so forth and so on and so forth.

These are potential problems in our code, and ESLint can effectively avoid these problems and improve the quality of our code.

On the other hand, I personally think ESLint can also help developers improve their coding capabilities. Why? Imagine writing code that finds a bunch of bugs every time lint runs, most of which are bad habits from past coding.

Gradually, you should remember these problems, and normally you will actively avoid them the next time you encounter them, so that over time your coding ability will naturally improve.

The bottom line is that ESLint is of great value both for improving the quality of your project’s coding and for improving your own coding.

ESLint installation

Using ESLint in the first place is to validate the project code, so we need to have a project first.

NodeJs is an NPM module, so to use ESLint, you need to install this module through NPM or YARN.

Finally, after the installation is completed, we can verify whether the installation operation is successful by simple command. After these steps are clear, we can go back to the development tool for concrete practical operation.

Here we open an empty sample project and initialize the project’s package.json file with NPM init –yes to manage the project’s NPM dependencies.

npm init
Copy the code

With package.json we can install the ESLint module, using in-project install dependencies.

npm install eslint --save-dev
Copy the code

As an aside, we rarely install an NPM module globally anymore, because most projects depend on a module, and it makes more sense to install the module locally and manage it along with the project.

In addition, after getting your project, others do not need to care about which global modules your project depends on. They can directly install the necessary tool modules through NPM Install, which also improves the maintainability of the project from the side.

Since esLint provides a CLI program, you can add an esLint executable file to the bin directory of node_modules after installing the ESLint module.

Later we can directly through the CLI program to monitor the problem in the code. Go back to the command line and find the esLint executable. Type –version and we see the version used by this ESLint.

cd node_modules
cd .bin
eslint --version
Copy the code

Node_modules tools in the bin directory can be quickly found using NPX or YARN without going to the specific directory.

If you are using yarn, you can run yarn ESLint directly, because YARN will automatically find the command in the bin directory. NPX is a new integrated tool of NPM, you will have the NPX command as long as the corresponding VERSION of NPM is installed.

npx eslint --version // yarn eslint --version
Copy the code

As an aside, don’t worry about whether to use NPM or YARN. There is no absolute difference between NPM and YARN. Each one has its own advantages.

ESLint is quick to get started

Create a new JS file in your project. We’ll call it main.js.

We intentionally missed fn by one) and then called a nonexistent function syy

const foo=123;

function fn() {
    console.log("hello");
        console.log("eslint); } fn( syy();Copy the code

There are some problems with the code, the format, and the rationality in main.js, so we’re going to find those problems by running ESLint, which we need to initialize the first time we run esLint.

npx eslint --init
Copy the code

The first question usually asks us how to use it. There are three options given here. The first is to check for syntax errors only, the second is to check for syntax errors and find problematic code, and the third is to check for syntax errors, find errors and verify code style. Obviously the third one is the most comprehensive.

Here we will talk about the specific meaning of these three functions.

The first syntax error is easy to understand. In our case, the call to the fn function is a syntax error because we are missing a parenthesis.

Problem code is code that doesn’t make sense, such as here we define an unused variable or call a function that doesn’t exist. This is all problem code.

The third code style is the easiest to understand. The initial expectation for ESLint was that it would find problems with sub-coding styles in code. For example, the indentation in our code is not uniform.

I’m sure you’ll get a sense of the concrete value of ESLint from here.

So knowing that we can make some choices here, let’s pick a third one here. In real code development, we also recommend choosing the third option, because it will ensure the best quality of your code.

After the selection is complete, the command line terminal presents the second question, which modularity is used in the project code, again there are three options.

The first one is ES Modules, the second one is CommonJS, which is the way require functions are done, and the third one doesn’t use any modularity. In a nutshell, the effect here is to determine whether your code allows certain syntax or calls to occur.

For example, if you choose CommonJS it allows you to use global require functions and exports objects. If you choose ES Modules it allows you to use export and import syntax. We don’t use modularity here, so we choose not to use any modularity.

There’s React and Vue. We’re going to choose Node for now. Nothing works.

Do you use typescript? If you do, type y. Default is N.

The fifth question asks which environment the code will ultimately run in. The default is a browser, where browser-node is selected. This is based on your runtime environment to determine whether the API is allowed to use that environment, in this case the browser is selected by default.

The sixth question asks how to define the code style. There are three choices: the first is to use the mainstream style in the market, the second is to form a style through some questions, and the third is to infer the style from the code file. In general, we use the prevailing code style on the market. In this way, if a new member joins our project, he can adapt to our style better and faster.

After the selection, three mainstream styles will be given here, namely Airbnb, Standard and Google. Airbnb and Google are the specific coding specifications of these two companies respectively, while Standard is a set of specifications of the open source community. This is the norm I personally use. Its biggest advantage is that it does not add semicolons to the end of statements. There are no standards, just follow the team’s standards. Let’s choose Standard here.

The last question asks what format the configuration file should be stored in. I prefer to use JS because I can add code and write more logic.

Hitting Enter will remind us that we need to install a few more plug-ins, because the style we just selected depends on some plug-ins.

After the installation, there will be an esLint configuration file,.eslintrc.js, in the root directory of the project. With this configuration file, we will verify our main.js file by executing the following command.

Eslint can also use the wildcard of the path to batch check files. After running esLint, files can be automatically checked for code.

npx eslint ./main.js
Copy the code

The result is that we checked for an error syntax error, that is, the function missing parentheses. We go back to the code to fix this error and execute ESLint again.

const foo=123;

function fn() {
    console.log("hello");
        console.log("eslint); } fn() syy();Copy the code

This time we will see more mistakes, you might wonder why just we didn’t find these errors, the reason is very simple actually, when there are grammatical errors in our code, eslint is that there is no way to check the code and code style, so this time you can according to the prompt to find specific questions on your own code. And then solve them in turn.

You can also automatically fix most code style problems with the –fix parameter.

npx eslint ./main.js --fix
Copy the code

The style code has been automatically corrected, very conveniently.

However, if you haven’t developed good coding habits, it is recommended to manually fix every bad point in the beginning, because this will enhance our impression.

As a good developer, we should write code that is well-formed and not rely on these tools to format it later. These tools are only used at the end of the day to ensure the quality of your code.

const foo = 123;

function fn () {
    console.log("hello");

    console.log("eslint); } fn() syy()Copy the code

In the end, we will see that there are two problems that have not been fixed automatically, and we need to go back to the code to deal with them manually. Here the foo variable is meaningless and the syy function is undefined. Delete both. Run the ESLint check again, and the code itself is all fixed.

Those are the basics of what ESLint does. In short, there are two points. First, ESLint can find problems in code, including syntax errors, code inconsistencies, and style inconsistencies. Second, ESLint automatically fixes most code style issues.

ESLint configuration file parsing

To take a closer look at the esLint configuration file, we created a.eslintrc.js configuration file in the project root directory using esLint –int.

The configuration that is written in this file will affect the current directory and all subdirectory files. Normally we do not modify this configuration manually, but this configuration file can be very important if we need to turn on or off certain validation rules.

Let’s take a look at the configuration content inside it. Let’s open up the configuration file and take a look. Since this file ends up running in NodeJS as well, you can see that an object is exported in CommonJS fashion.

module.exports = {
    env: {
        browser: true.es2020: true
    },
    extends: [
        'standard'].parserOptions: {
        ecamVersion: 11
    },
    rules: {}}Copy the code

There are currently 4 configuration options in this configuration object, the first of which is called env. We all know that JavaScript has different apis that can be called in different runtime environments, and these apis are often provided as global members. For example, in the browser environment we can directly use window and document objects, but in the NodeJS environment these objects do not exist.

The env option marks the final environment in which your code will run. Eslint will use the environment information to determine whether a global member is available or not to avoid using non-existent members in your code. For example, browser being true here means that the code will run in the browser environment. This means that we can use global objects like Document or window directly in our code.

In other words, the idea here is that each environment corresponds to a set of predefined global variables, and once an environment is enabled all global members of that environment are allowed to be used directly.

Let’s try it out here. Let’s add delete browser or set browser to false and run the main.js code below.

document.getElementById('#abc');
Copy the code

But when we run it, we don’t get a document undefined error, basically because when we regenerated the ESLint configuration we chose the Standard style, and we ended up inheriting the Standard configuration, In standard this style to do some specific configuration, document and window in any environment is to use.

We can also go to the standard configuration to verify this, we can go to node_modules eslint-config-standard directory, which has an eslintrc.json file, which wins the document, navigator, Window is set to a member that is read-only globally.

"globals": {
    "document": "readonly"."navigator": "readonly"."window": "readonly"
}
Copy the code

This configuration is inherited by our configuration file, so our env does not affect the use of document. We can try calling alert, which is undeclared.

alert(11);
Copy the code

An alert undefined error is reported, which proves that the env option does determine whether a global member is available based on the environment.

Env can set up the following environments

Browser: global variable in the browser environment

Node: nodejs global variable and scope

Commonjs: CommonJS global variables and CommonJS scopes (for Browserify/webpack only code running in the browser)

Shared-node-browser: a global variable used by NodeJs and browser.

Es6: Enable all ECMAScript6 features except modules, which automatically sets the ecmaVersion parser option to 6.

Worker: Web Workers global variable.

Amd: Define require and define as global variables like AMD.

Mocha: Adds all mocha test global variables.

Jasmine: Added all test globals for Jasmine version 1.3 and 2.0.

Jest: JEST global variable

Phantomjs: PhantomJS has changed globally

Protractor: Protractor global variable

Qunit: The qunit global variable

Jquery: jquery global variable

Prototypejs: prototype-js global variable

Shelljs: Global shellJS variable

Meteor: global variable of meteor

Mongo: MongoDB global variable

Applescript: Applescript global variable

Nashorn: Java 8 Nashorn global variable

Serviceworker: Service Worker global variable

Atomtest: Atom tests global variables

Embertest: Ember global variable

Webextensions: The webextensions global variable

Greasemonkey: Greasemonkey global variable

Note that these environments are not mutually exclusive, which means that you can have multiple environments enabled at the same time. For example, we can set browser and Node to true so that all global members in both environments can be used at the same time.

module.exports = {
    env: {
        browser: true.node: true.es2020: true
    },
    extends: [
        'standard'].parserOptions: {
        ecamVersion: 11
    },
    rules: {}}Copy the code

The extends extends extends extends. This option is used to inherit shared configurations. If you need to share an ESLint configuration across multiple projects, you can define a common configuration file or configuration module and then inherit from there. The property value is an array, and each item in the array is a configuration.

ParserOptions sets up the syntax parser. We know that ECMAScript has been released many times in recent years. This configuration allows the use of a certain ES version of the syntax. This is ECMAScript2020.

If we set ecamVersion to 5, we won’t be able to use the new ES6 feature at this point. It’s important to note that sourceType can’t be module if ecamVersion is lower than 6, because ES Modules are new to ES6. Here we need to change the sourceType in the Standard configuration to script.

ParserOptions does not indicate whether a member is available or not. If it is a global member provided by ES2015, such as Promise, it still needs to be controlled by ES6. Then set es2015 in env to false.

module.exports = {
    env: {
        browser: true.es2015: false
    },
    extends: [
        'standard'].parserOptions: {
        ecamVersion: 2015
    },
    rules: {}}Copy the code

ParserOptions only checks syntax, not whether a member is available. The specific member is defined by the context.

After that let’s look at the rules configuration. This property is used to enable or disable each rule in ESLint. For example, we can try to enable the no-alert rule here. To enable this function, add an attribute in rules. The attribute name is the built-in rule name. The value of the attribute can be off, Warning, or error. Off indicates that the rule is closed, warning indicates that a warning is issued, and error indicates that an error is currently reported. In this case, error.

module.exports = {
    env: {
        browser: true.es2015: false
    },
    extends: [
        'standard'].parserOptions: {
        ecamVersion: 2015
    },
    rules: {
        'no-alert': "error"}}Copy the code

Once set up, the code that uses alert will report an error. That’s what the rules property does. What rules can be used specifically? The esLint website provides a list of all the built-in validation rules available so you can view them as you use them. The standard style we’re currently using already opens up a lot of rules. Basically also meets all the requirements, if there is a need to carry out specific configuration according to their own needs.

Finally, there is the globals option, which is no longer present in the latest version of the default configuration. Let’s briefly explain that this option is easy to understand, which is to declare additional global members that we can use in our code.

For example, in a project that uses JQuery, it is common to use a global JQuery object. You can simply add a JQuery object and set its value to readonly, so that JQuery can be used directly in your code without error. This is where the Globals option comes in, allowing us to customize our configuration accordingly.

module.exports = {
    env: {
        browser: true.es2015: false
    },
    extends: [
        'standard'].parserOptions: {
        ecamVersion: 2015
    },
    rules: {
        'no-alert': "error"
    },
    globals: {
        jQuery: 'readonly'}}Copy the code

The above is a detailed explanation of the specific configuration items in our ESLint configuration file.

ESLint configuration comments

Here we’ll look at configuration comments for ESLint. In simple terms, configuration comments can be interpreted as writing configuration directly into our script file as a comment and then performing code validation.

Why do you do that? The reason is very simple, for example, if you use ESLint in actual development, you will inevitably encounter one or two configuration rules violations, in which case you should not override the configuration of the validation rules just because of one or two points. So at this point we can use ESLint configuration comments for validation rules to solve some of these problems.

Let’s say we define a normal string and use a literal placeholder like ${} for business purposes, but our standard style doesn’t allow us to use it this way.

To solve this problem, you can use comments to temporarily disable such a rule. There are various syntax for such comments, refer to the documentation provided by ESLint. We use eslint-disable-line directly here, so that we ignore this line of code when ESLint is working.

const str = '${name} is a coder'; // eslint-disable-line
console.log(str);
Copy the code

Using this method can solve the problem we are facing, but it also introduces a new problem. If there are multiple problems in a row, all problems will not be detected. It would therefore be better to follow eslint-disable-line with the name of the specific rule to disable. For example, this is no-template-Curly -in-string.

const str = '${name} is a coder'; // eslint-disable-line no-template-curly-in-string
console.log(str);
Copy the code

Only the specified problem rule is ignored, and other problems can still be found.

Of course, annotations can not only disable a rule, but also declare global variables, modify the configuration of a rule, temporarily open a certain environment and so on. If you need these functions, you can go to the following link to find the corresponding document to query the corresponding use.

http://eslint.cn/docs/user-guide/configuring#configuring-rules
Copy the code

Here’s an introduction to ESLint configuration comments.

Webpack integration ESLint

If you are currently developing a webPack-wrapped project, ESLint can also be integrated into it, but webPack integration with ESLint is not done as a plug-in, it is done through the Loader mechanism. We all know that WebPack sends modules it encounters to the corresponding Loader for processing before packaging them.

So ESLint can be integrated into webpack as a loader, so that javascript code can be verified by ESLint before it is packaged.

We first need to install the corresponding ESLint module and esLint-Loader module. And initialize the.eslintrc.js configuration file.

npm install eslint eslint-loader -D
Copy the code

With that done, we can go back to the project to implement subsequent content actions. Here we first find the webpack configuration file, which all js files are handed to babel-loader for processing.

If we want to integrate ESLint, we also need to process js files before babel-loader.


module.exports = {
    mode: 'production'.entry: './src/main.js'.module: {
        rules: [{test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: ['style-loader'.'css-loader'}]}}Copy the code

Since we have already installed the corresponding module, we can configure it directly in the webPack configuration file. Here we configure js loader as an array, and place eslint-loader at the end. That is, the last configuration is executed first.

Or we can use another configuration method, which is to add a separate loader rule to the js file. In this rule, we can add an enfore attribute and set its value to pre to ensure that the priority configured for this loader is higher than that configured for other loaders. This can also be implemented to pass ESLint validation. And then go perform one of Babel’s transformations.

We can use both of these two methods in operation. I personally recommend using the second method, because such configuration will be clearer. We will use the second method to complete such use. Add the JS configuration to a loader.


module.exports = {
    mode: 'production'.entry: './src/main.js'.module: {
        rules: [{test: /\.js$/,
                exclude: /node_modules/,
                use: 'eslint-loader'.enfore: 'pre'
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: ['style-loader'.'css-loader'}]}}Copy the code

When we use Webpack after this configuration, we will get an ESLint error. This enables esLint to be integrated into the WebPack. Very simple.

React has JSX syntax, so the configuration of ESLint can be complicated. Here we introduce how to use esLint-Loader to integrate esLint into the webPack project. In the subsequent use, we will conduct specific and separate processing operations.

After that, we’ll take a look at the following configuration operations related to the integration of ESLint into WebPack and check the code with webPack operations.

Eslint automatically uses rules to validate our javascript code when we use Webpack packaging.

We all know that ESLint will check for a lot of things that are defined but not used, such as React is define but never used. However, we know that React is used after JSX is compiled, so in special cases like this, ESLint would have to rely on additional plugins to implement it.

There is a plugin for the React syntax called eslint-plugin-react. We need to install this module into our local development dependencies.

npm install eslint-plugin-react --save-dev
Copy the code

After installing node_modules, you’ll find that node_modules has a lot of rules that are specific to react projects. If we want to use these rules, we go directly to the ESLint configuration file and configure them using the plugins property.

Plugins are arrays that specify which plugins to use. The plugin module here is called eslint-plugin-react. Add react to this array because the module name removes the eslint-plugin-

When this is done, the rule can be used. Use react/jsx-uses-react in rules. You can use error or you can use the number 2 for error. The purpose of this rule is to avoid an error defined by React but not used.

module.exports = {
    env: {
        browser: true.es2020: true
    },
    extends: [
        'standard'].parserOptions: {
        ecamVersion: 11
    },
    rules: {
        'react/jsx-uses-react': 2.'react/jsx-uses-vars': 2,},plugins: [
        'react']}Copy the code

This is what plugins do and how they are used in general. However, most ESLint plugins generally provide a shared configuration to reduce the cost of using them. Here we use eslint-plugin-React, which exports two shared configurations: Recommend and all. We generally use Recommend, which provides shared configurations that we can use directly through inheritance.

However, we should follow the syntax rules when inheriting. Specifically, we can use plugin: plugin name/config name to complete the use.

module.exports = {
    env: {
        browser: true.es2020: true
    },
    extends: [
        'standard'.'plugin:react/recommend'].parserOptions: {
        ecamVersion: 11}}Copy the code

In this way, the content of shared configuration does not need to be configured separately, and it will be more convenient to use. This is where ESLint inherits from Webpack.

Check ESLint TypeScript

Here we take a look at ESLint’s syntagmatic support for TypeScript. With more and more development using TypeScript in front end projects, we’ll take a look at how ESLint validates TypeScript code.

To start with, lint in TypeScript used to operate with a tool called tsLint. However, since the tsLint official website has been abandoned, It is then suggested that we use ESLint with typescript plugins to validate typescript code.

With that said, let’s take a closer look at ESLint’s validation support for TypeScript syntax. First we still need to initialize ESLint. When it comes to TypeScript selection, we choose Y instead of N. There are also two modules that esLint needs to install to check TypeScript code, which are installed automatically.

After installation, you can use ESLint to check TypeScript code.

function foo (ms: string) :void {
    console.log(ms);
}

foo('hello typescript~')
Copy the code

Let’s look at the.eslintrc.js configuration option. The parser function here is to specify a syntax parser. The reason we need to configure a syntax parser is that TypeScript has a lot of special syntax compared to normal JavaScript code, so we need to specify a syntax parser for it.

module.exports = {
    env: {
        browser: true.es2020: true
    },
    extends: [
        'standard'].parser: '@typescript-eslint/parser'.parserOptions: {
        ecamVersion: 11
    },
    plugins: [
        '@typescript-eslint'].rules: {}}Copy the code

With that done, you can verify the TypeScript code to find problems. This is how ESLint checks TypeScript and some of its operations.

Stylelint check CSS

Here’s how to use stylelint. We all know that CSS code also needs to be lint in front-end projects as well as javascript code. For CSS code, we usually use a tool called stylelint to handle lint.

The use of stylelint is essentially the same as esLint mentioned earlier.

First of all, stylelint also provides a series of code checking rules for direct use. As before, we can optionally turn on or off certain rules in the configuration file.

Stylelint also provides a CLI tool. You can call the stylelint command directly from the terminal and then check the CSS files in the project.

Furthermore, the stylelint can also be checked for csS-derived syntax through plug-ins such as Sass less postCSS.

Finally stylelint can also be integrated with gulp automation tools or packaging tools such as WebPack.

Knowing this, it should be clear that using the Stylelint can be completely guided by esLint because they are very similar to each other. Here’s a quick guide to stylelint.

First you need to install the stylelint module, and then you can use the STYLelint CLI command.

npm install stylelint -D
Copy the code

After installation we also need to configure stylelint, similar to ESLint, the style file is named.stylelintrc.js, which we add manually. The properties in this configuration file are basically the same as those in Eslintrc.

Here we install the shared configuration module stylelint-config-standard.

npm install stylelint-config-standard -D
Copy the code

After installation, use it directly as an inheritance, unlike esLint where the shared module name must be the name of a full module. That means that what we have here has to be

module.exports = {
    extends: "stylelint-config-standard"
}
Copy the code

Once this configuration is complete, we inherit the configuration module and then execute the stylelint command.

npx stylelint ./index.css
Copy the code

These problems can be identified and corrected directly, or let stylelint do most of the automatic fixing for problems with the –fix parameter as before.

This is the introduction to stylelint configuration and use. Now let’s talk about checking the SASS code. If you want to use stylelint to check the SASS code in our project, you can certainly do so.

Here we need to install stylelint-config-sass-guidelines

npm install stylelint-config-sass-guidelines -D
Copy the code

Configure the extends property after installation, and then you can use the StylelInt to detect SASS code.

module.exports = {
    extends: ["stylelint-config-standard"."stylelint-config-sass-guidelines"]}Copy the code

In addition to these, there are other less or postCSS that operate similarly and we won’t go into detail here. If you want to integrate stylelint into a workflow like gulp, you can also refer to esLint’s integration method. Because they are all very similar operations.

The above is our understanding of stylelint. There is nothing in esLint or Stylelint itself that is difficult. The key is to learn how to do the same thing. For example, after you learn javascript’s Lint tool, will you be able to find a corresponding lint tool for your CSS or HTML?

Prettier automatically fixes code problems

Prettier is the most common front-end code formatting tool prettier has used in the past two years. Prettier can format almost all front-end code files and format code automatically in daily use. Or format for a document like Markdown.

Prettier is easy to standardize in front-end projects by using prettier and is simple to use. Next, let’s take a look at some of his specific use operations. How to use Prettier to format code directly.

First we need to install Prettier, usually in a development dependency.

npm install prettier -D
Copy the code

After the installation is complete we can format our code directly using the prettier command. Here you can follow a file path.

npx prettier style.css
Copy the code

By default, this command outputs the formatted code directly to the console. Normally, we need to overwrite the formatted code to the source file. We can do this by following the –wirte parameter in the command.

npx prettier style.css --write
Copy the code

Prettier format all files by using the wildcard command, for example, formatting all files.

npx prettier . --write
Copy the code

Prettier that’s why Prettier is so easy to use, prettier can be found by calling an argument to the file where prettier is found.

Finally, we hope that we do not completely rely on this tool to write some well-formed code, because we should strictly abide by these formats in the process of coding, which is the most basic quality for us as developers.

Git integration ESLint

For now we all already know our code a importance of standardization, at the same time we also know how to through the use of tools to ensure that our code specification is how to fall to the ground, but in the process, there are still some missing problem, for example, if one of our team members are in accordance with the requirements to use lint tools. Or he forgot to use lint at all. Finally, the problematic code was submitted to our remote warehouse. In this case, when we carried out project integration in the later stage, the code of our whole project might not be approved by CI.

So at this point our Lint tool loses its meaning. In itself, we use Lint to make sure that the code we put into the repository is fine. And the format is good. So how can we solve this problem.

If we simply rely on verbal constraints that require team members to execute Lint before committing code, it would be a mere formality, so a better approach would be to somehow force code to be checked by Lint before committing. That’s the value of Githooks.

Here’s a quick look at githooks.

Githooks are also known as Git hooks. Each hook is associated with some specific Git operations, such as commit and push. Secondly, you can directly find a specific hook and write some specific shell scripts. Then we define some tasks that our Git hook will perform when it fires.

But here we have a very real problem, many developers today are not very good at using shell scripting. The current feature is one we must use. So someone developed an NPM module.

A simple implementation of Githooks is called husky, which allows you to use githooks without having to write shell scripts.

To use Husky, you need to install the Husky module as a development dependency.

npm install husky --save-dev
Copy the code

This will automatically add custom hooks to the.git/hooks directory, so we don’t have to worry about how to implement them or look at them.

Json file, in which we define an hooks object. Then, inside the hooks object, we can directly define the hooks for different tasks.

All we care about here is the operation before the commit, so we add a pre-commit with the value of an NPM command. This will help us find the test command in the script when we perform the commit.

{..."scripts": {
        "test": "eslint ."
    },
    "husky": {
        "hooks": {
            "pre-commit": "npm run test"}}... }Copy the code

Basic know, now we are about the use of the husky module, specifically we can directly in the configuration file of our new a husky field, and then in him for specific hooks to set the command to execute, which can perform some NPM operation in the future time can be set to call good command.

How can we use this rule to make our code perform a lint operation before committing, which is as simple as executing the NPM run test command? That’s how husky works. This already allows us to validate the code before committing.

But if we want to continue after the inspection, for example, we want to format the inspected code or simply add the formatted code to the staging area. That’s when Husky starts to look inadequate.

The lint-stage module can be used in conjunction with Husky to further improve some of its other functions, so here’s a look at some of its uses. First we need to install this module.

npm install lint-staged --save-dev
Copy the code

Json file. Add a Lint-staged attribute and set a *.js attribute inside the package.json file. This attribute can be an array of successively performed tasks. For example, by adding an ESLint and then setting git add, we’re setting up two commands.

We also need to set scripts to be executed by the precommit hook into lint-staged scripts, but we need to note that since we changed the name of this hook to precommit, we will still have to go to our husky, Change the NPM command to precommit

Also specify specific tasks for him to accomplish. So with that we’re going to go back to scripts and set up the script.

{..."scripts": {
        "test": "eslint ."."precommit": "lint-staged"
    },
    "husky": {
        "hooks": {
            "pre-commit": "npm run precommit"}},"lint-staged": [
        "eslint"."git add"]... }Copy the code

After this is configured, the commit will trigger NPM run precommit, which will perform esLint and Git add operations in precommit. This allows us to impose lint on our code before committing, while we can complete the following requirements.

That’s how githooks works with ESLint. Husky in combination with Lint-staged is generally recommended, as this way we can not only enforce validation of our code prior to commit, but we can also do something else after or before validation.


This article is my own study notes, unoriginal article, main source for hook education, ESLint official, Github