Touch fish sauce article statement: content guarantee original, pure technology dry goods to share exchanges, do not play advertising do not brag force.

Introduction: I remember when I first participated in the development of the company’s project, I was diss by my colleagues because the code structure was too chaotic, and then I was urged to open ESLint to develop, but I fell into the clutches of ESLint. But when I opened ESLint, I really f * * k it, the code went viral everywhere, and THEN I secretly shut esLint down (wit me <())>). But sure enough, it wasn’t long before I was caught again. After a few cat-and-mouse games, I finally got used to esLint and liked it.

I won’t spend too much time in this article on the use of Eslint, because that’s what official documentation does. What I’m hoping to do is, after reading this article, you’ll be able to step outside of Eslint itself and see the requirements that it implements, namely code checks that implement JS/TS. Next, I’ll use the need to implement code checking as a starting point to introduce four code checking poses for code ESLint.

As for the requirements of code inspection and its implementation scheme, I made the following arrangement based on my personal understanding and brain map:

I’ll focus on this brain map for the rest of the article, and I hope you’ll stick with it a little longer if you’re interested in looking at it further.

Ok, according to the logic of the above brain map, I will divide this paper into the following parts.

  • Understand code review
  • Implement code checking for project access to Eslint
  • Implementation of < Post-code check > based on Eslint and its rules
  • Implementation of < code check > based on Eslint and its rules
  • Implementation of “Pre-Build Checking” based on Eslint and its rules
  • Implementation of Eslint and its rules

Ok, now that we’ve cleared up the writing, let’s move on to the first part, understanding code review.

One: Understand code reviews

Code checking, as the name implies, occurs during the development phase and can help developers reduce careless JavaScript code such as syntax errors, undefined variables, unused variables, and so on. In addition, code review can also unify the code style of developers and facilitate team collaboration.

After this paragraph, we have reached a conceptual understanding of code review. Let’s start with three more aspects of the analysis to deepen the practical understanding of code review. The three aspects are as follows:

  • Code check function
  • Type of code checked
  • A tool for code review

Ok, let’s start with the discussion of code inspection.

1. Function of code inspection

I think that code checking this aspect probably helps us do three things:

  • Language syntax check: Check for string quotes or function call parentheses that do not match.
  • Coding error checking: for example, checking that the developer is using a variable that does not exist or that is defined but not used.
  • Code style check: For example, check that the developer is not using semicolons (depending on the style chosen).

Summary: The level of the section determines the function of the section.

Now that you understand what code checking can do for this aspect, let’s look at the types of code checking.

2. The way code is checked

Based on the different times and scenarios in which code review takes place, I have classified code review methods into the following four categories:

  • Code-time checking: Code-time checking, usually represented by the IDE automatically checking and prompting code in real time.
  • Post-code check: Post-code check, usually in the form of manually invoking a check script/tool to check the code or automatically checking the current file by the IDE after the code is saved.
  • Pre-build inspection: Pre-build inspection, usually represented by code inspection as a pre-built aspect of the build task, is automatically triggered at build time.
  • Git commit check: Git commit check, typically as an hooks task that automatically triggers code checks before committing.

Doesn’t such selfless sharing deserve a few likes and attention?

It’s important to understand how code review works, as it is a direct reflection of how well you understand the concept of code review itself. Without further ado, let’s enter the discussion of code inspection tools.

3. Code checking tools

The implementation of code checking is often more than just string parsing; there is a lot of parsing involved. Since syntax is involved, different code checking tools need to be used for different types of code. In general, we use the Eslint tool for checking JavaScript and Typescript code, and the stylelint tool for checking style code. Instead of writing about Stylelint in this article, let’s turn the stage to Eslint to explore how Eslint can check JavaScript and typescript code.

Ok, before we discuss post-code check, cod-on-code check, pre-build check, git pre-commit check in order, let’s plug in Eslint for the project and configure the check rules that are required for each type of code check.

Two: Implement code checking for project access to Eslint

For those of you who may not be familiar with Eslint, let’s give it a brief introduction.

Eslint is a plug-in (rule-checking) JavaScript code checker. Note that esLint is a plug-in checker, which means that esLint is designed to decouple checkers from checkers. That is, after installing esLint’s development dependencies, we can and need to choose to install a checking rule of our choice.

Ok, so much for theory, then we can get insights from practice, which is as follows:

Step1: install the checking tool eslint

yarn add eslint --dev
Copy the code

Step2: install and configure check rules

Before we explore the configuration of the installation inspection rules, it is important to clarify what our inspection objectives are. In my opinion, the inspection target is naturally pre-build code, and code written by myself/my team (not third-party modules). After all, the ultimate goal of inspection is to fix, we are only responsible for fixing our own/our own team’s code, build code and third party code even if the inspection does not pass we will not and should not fix.

Inspection rules usually take two forms in a project, namely:

  • Rules configured in a configuration file: The main form, which declares a large number of rules through inheritance and extension
  • Magic comments in project code: A minor form, usually used as a special case for rules in configuration files

Generate the ESLint configuration file:

For configuration files, we would normally use the eslint –init command to generate this configuration file. The following table lists some of the configuration problems that often occur after calling this command (not necessarily in the following order).

Note: I find it prudent to answer these questions because the answer affects the configuration, the configuration affects the check rules, and the check rules affect the check results. Of course, the purpose of answering these questions is to generate the desired configuration file, but you can also directly modify the ESLint configuration file if you get the question wrong or make subsequent rule changes.

The serial number role The problem
1 Select a use to use ESLint, often 3 How would you like to use ESLint? (Use arrow keys)

    To check syntax only

    To check syntax and find problems

    To check syntax, find problems, and enforce code style
2 Select the modular specification to use for the project What type of modules does your project use? (Use arrow keys)

    JavaScript modules (import/export) only

    CommonJS (require/exports)

    None of these
3 Choose the framework to use for the project Which framework does your project use? (Use arrow keys)

    React

    Vue.js

    None of these
4 Whether to use Typescript Does your project use TypeScript? (y/N)
5 Select the environment in which the code will run (multiple options) Where does your code run? (Press <space> to select, <a> to toggle all, <i> to invert selection)

    ( ) Browser

    ( ) Node
6 Choose how to define the style for your project How would you like to define a style for your project? (Use arrow keys)

    Use a popular style guide

    Answer questions about your style

    Inspect your JavaScript file(s)
7 Choose to use specific popular code styles Which style guide do you want to follow? (Use arrow keys)

    Airbnb (Github.com/airbnb/java…

    Standard (Github.com/standard/st…

    Google (Github.com/google/esli…)
8 Select configuration file format, usually 1 (more flexible) What format do you want your config file to be in? (Use arrow keys)

    JavaScript

    YAML

    JSON

Magic comments in code:

In addition to configuring rules in configuration files, ESLint also has a way of using magic comments to patch rules in code, as shown in the following example:

// Mask entire lines of code inspection
const str1 = "${name} is a coder" // eslint-disable-line
// Mask a rule: such a no-template-curly-in-string rule
const str1 = "${name} is a coder" // eslint-disable-line no-template-curly-in-string 
Copy the code

Warning: The rule name can be obtained from the check result or the output information

Implementation of Post-code check based on Eslint and its rules

For an explanation of a workflow, I prefer to go straight to a simple demo. With that in mind, here’s an example of Eslint checking JS code and an example of Eslint checking TS code. According to the logic of the code review, I will follow the following ideas in the demo and presentation, namely:

  • Target problem code
  • Code check rule configuration
  • Code checks actions and results
  • Fixing code actions

Ok, so let’s get into Eslint’s discussion of post-code checking of JS code.

1. Check JS code examples after Eslint is encoded

1): Target problem code

const noUsedVar = 1;

function fn(a) {
  console.log('hello')

  cnsole.log('eslint');
}

fn(

fn2();
Copy the code

These few lines of code represent the three parts of the Eslit code review, which are:

  • Grammar mistakes
  • Encoding error: undefined, unused
  • Coding style: No semicolons

2): code check rule configuration

With esLint –init, the resulting ESLint configuration file will look like this after answering the question based on the project characteristics:

module.exports = {
  env: {
    browser: true,
    es6: true,
  },
  extends: [
    'airbnb-base',
  ],
  globals: {
    Atomics: 'readonly',
    SharedArrayBuffer: 'readonly',
  },
  parserOptions: {
    ecmaVersion: 2018,
  },
  rules: {
  },
};
Copy the code

3): Code checks operations and results

The first round of checks reported syntax errors. After fixing syntax errors, the second round of checks reported many coding and style errors. Correlating the results of the two checks to the problem code yields the following analysis:

const noUsedVar = 1; / / find the program:'noUsedVar' is assigned a value but never used

function fn(a) {
  console.log('hello') // Enforce code style: Missing semicolon cnsole.log('eslint'); / / find the program:'cnsole'is not defined } fn( // syntax error fn2(); / / find the program:'fn2' is not defined
Copy the code

4): Fix the code

Repair according to the above examination results. For code style inconsistencies, the –fix parameter automatically fixes most of the problems. Syntax and coding errors are mostly fixed manually by developers. After manual and automatic fixes, the problem code might look like this:

import { fn2 } from './test2';

function fn(a) {
  console.log('hello');

  console.log('eslint');
}

fn();

fn2();
Copy the code

2. Check the TS code examples after Eslint is coded

1): Target problem code

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

foo("hello typescript~")
Copy the code

2): code check rule configuration

After installing typescript dependencies on your project (eslint –init will report an error if you do not install typescript dependencies first), use the eslint –init command to answer the question based on the project characteristics (typesrcipt yes) and get the following ESLint configuration file:

module.exports = {
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": [
        "airbnb-base"]."globals": {
        "Atomics": "readonly"."SharedArrayBuffer": "readonly"
    },
    "parser": "@typescript-eslint/parser"."parserOptions": {
        "ecmaVersion": 2018
    },
    "plugins": [
        "@typescript-eslint"]."rules": {}};Copy the code

Typescript checking requires an additional syntax parser (the parser configuration item content in the configuration above) than JavaScript code checking.

3): Code checks operations and results

After checking with –fix, ESLint mainly reports two coding errors, which are mapped to files as follows:

function foo(ms: string): void {	// 'ms' is defined but never used 
  console.log(msg);	// 'msg' is not defined
}

foo('hello typescript~');
Copy the code

4): Fix the code

In this example, after fix fixes the code style automatically, manually change the parameter of the foo function to MSG.

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

foo('hello typescript~');
Copy the code

Implementation of “Code check” based on Eslint and its rules

When it comes to coding checks, we have to refer to code hints, and we have to refer to the IDE we choose to use. In addition, to ensure uniform configuration of code checking rules in multiple ways, a key point is that the IDE can read the ESLint rule files that we configured in the project to check code in real time.

Since I mainly use VScode for development, the following demo and discussion will be in VScode environment by default. Visual Studio Code: Eslint Extension documentation is available in the official list of Eslint integration tools.

To be honest, I also sell this stuff as I learn it. After all, there are so many things to learn at the front end, and the original intention of this article is not to cover every aspect of a technical point, but to help you establish a systematic understanding and guidance.

Because we need to be able to read esLint rules under the project during IDE live code checks. So the following two steps are essential:

  • Install ESLint and configure ESLint rules
  • IDE real-time code check features related to the installation and configuration

According to the above implementation steps, let’s make a vscode environment, based on Eslint and its rules to implement the code check demo.

1. Install ESLint and configure ESLint rules

yarn add eslint --dev	# installation
eslint --init	Initial configuration
Copy the code

The way ESLint can configure rules has been discussed above and won’t be covered here.

2.IDE real-time code check function related installation and configuration

After the ESLint tool and the checking rules are ready (the rules for IDE code checking), it’s up to the IDE to do the actual checking behavior triggering and code prompting. For vscode, the idea here is to install the eslint extension (for personal use version 2.1.14, the following configuration 1.x May not be applicable), Vscode esLint code check (the ESLint switch under VSCode is marked with esLint text in the lower right corner)

Configure IDE real-time checking

If you need to configure the LIVE checking feature of the IDE, you can go to vscode setting -> find ESLint -> open setting.json to find the relevant configuration file. Here is an example of configuring vscode code checking:

/ / configuration eslint"editor.codeActionsOnSave": {// Automatically fix when saving"source.fixAll.eslint": true
    },
    "eslint.quiet": true, // Warning is not marked with a red underscore, which can be used to process no-consoleWarning of rule explosionCopy the code

Real – time code check after bug fixes

When the IDE automatically checks for code that violates a rule, you can modify the check rules file (.eslintrc.js) under your project. ESLintExpected linebreaks to be ‘LF’ but found ‘CRLF’ rule error ESLintExpected linebreaks to be ‘LF’ but found ‘CRLF’ rule error ESLintExpected linebreaks to be ‘LF’ but found ‘CRLF’ rule error ESLintExpected linebreaks to be ‘LF’ but found ‘CRLF’ Specific reasons will not be analyzed here, but individuals can directly add the following rules in the rules file (.eslintrc.js) to solve the problem:

 rules: {
    'linebreak-style': [0.'error'.'windows'],},Copy the code

Implementation based on Eslint and its rules

Let’s dive right into how the most commonly used gulp and WebPack build tools implement pre-build checking.

1. Check gulP before construction

The idea behind implementing this code through gulp is as follows:

  • Install ESLint and initialize the ESLint configuration file
  • Download and install gulp-esLint
  • Write js file processing code to check the section

1): Initializes the ESLint configuration file

yarn add eslint --dev
eslint --init
Copy the code

2): Download and install gulp-esLint

yarn add gulp-eslint --dev
Copy the code

3): write js file processing code to check the section

The following is an example:

/ /... Const eslint = require()'gulp-eslint');

const script = (0= > {return src(['scripts/*.js']).pipe(eslint()) // code check.pipe(eslint.format()) // prints lint results to the console. .pipe(eslint.failafterError ()) // Lint exits the process and ends the build. .pipe(babel({ presets: ['@babel/preset-env']}))
	        .pipe(dest('temp')) .pipe(bs.reload( { stream: true } )) } // ... Other codeCopy the code

2. Check webpack before building

The idea behind using Webpack to implement this code inspection aspect is as follows:

  • Install ESLint and initialize the ESLint configuration file
  • Install eslint – loader
  • Write the webPack configuration file and add the eslint-loader to the JS file

(1): Install ESLint and initialize the ESLint configuration file

yarn add eslint --dev
eslint --init
Copy the code

(2) : install eslint – loader

yarn add eslint-loader --dev
Copy the code

(3): Write the webPack configuration file and add the eslint-loader to the JS file

rules: [
	{
		test: /.js$/,
		exclude: /node_modules/,
		use: [
			'babel-loader'.'eslint-loader'	// The last one is executed first]}]Copy the code

Git Check before Committing

In this section, I’ll take a step-by-step look at how Eslint implements git pre-commit checking from four aspects:

  • 1. Check before git commit
  • 2. Implementation with Husky: Write node code instead of shell code
  • 3. Hook task flow: Lint-staged cooperation with Husky
  • 4. Implement git pre-commit checking: execute the ESLint task and then the Git add task

Git Hooks. Git Hooks.

1. Check before git commit

Eslint implements git pre-commit checks using git Hooks, which correspond to a single task. Using shell scripts, you can write the actions that need to be performed when the Hook task triggers.

This article focuses on code checking before git commit, so we focus on the git commit hook, using the following steps:

  • Create a new pre-commit file in the. Git /hooks folder of your project
#! /bin/sh
echo "before commit"
Copy the code
  • Trigger hook: Execute git commit in your project

After the git commit command is executed, you can view before commit information regardless of whether the commit operation succeeds.

After all, it is difficult for front-end developers to use shell scripts to write Git hooks. Here we introduce husky library to help us achieve the purpose of writing hook tasks in JS code.

2. Implementation with Husky: Write node code instead of shell code

The implementation steps are as follows:

  • (1) : installation of husky
  • (2): Configure husky hook tasks as follows: package.json tasks
  • Git add -> git commit

1) : installation of husky

yarn add husky --dev
Copy the code

Once the module is installed, you should see the following newly added files in the.git/hooks folder.

2): Configure husky hook tasks as follows: package.json tasks

  "scripts": {
    "test1": "echo before commit"."test2": "node test2.js"
  },
  "husky": {
    "hooks": {
      "pre-commit": "yarn test2"}},Copy the code

3): Trigger hook: git add -> git commit

Git commit triggers the hook task that we implemented with HUSky in JS code.

Let’s enhance hooks from lint-staged libraries to support firing of task flows as well as single tasks.

3. Hook task flow: Lint-staged cooperation with Husky

The implementation steps are as follows:

  • (1): Install HusKY and Lint-Staged modules
  • (2): Configure the flow of Husky hook tasks: package.json tasks as follows
  • Git add -> git commit

1): Install HusKY and Lint-staged modules

yarn add husky --dev
yarn add lint-staged --dev
Copy the code

2): Configure the flow of Husky hook tasks as follows: package.json tasks

"scripts": {
    "precommit": "lint-staged"
},
"husky": {
    "hooks": {
        "pre-commit": "yarn precommit"}},"lint-staged": {
	"*.js": ["echo task1"."echo task2"."echo task3"]}Copy the code

3): Trigger the task flow: git add -> git commit

In practice, git commit commands will only trigger actions in The Lint stage if they are successfully executed (with add resources and commit information), as compared to a single task implemented by a separate HusKY module, and these actions will only be valid for JS files.

Ok, after the above preparation, now we can enter the final requirement we want to implement, namely implementing git pre-commit check discussion.

4. Implement git pre-commit checking: execute the ESLint task and then the Git add task

The implementation steps are as follows:

  • (1): Install HusKY and Lint-Staged modules
  • (2): Configure the flow of Husky hook tasks: package.json tasks as follows
  • Git add -> git commit

1): Install HusKY and Lint-staged modules

yarn add husky --dev
yarn add lint-staged --dev
Copy the code

2): Configure the flow of Husky hook tasks as follows: package.json tasks

"scripts": {
    "precommit": "lint-staged"
},
"husky": {
    "hooks": {
        "pre-commit": "yarn precommit"}},"lint-staged": {
	"*.js": ["eslint --fix"."git add"]}Copy the code

3): Trigger the task flow: git add -> git commit

After downloading and configuring these development kits, husky configuration pre-commit hook tasks were triggered after git COMMIT, which in turn turned over the task to Lint-staged processing. Lint-staged code inspection of JS files and re-add after automatic style repair (which will interrupt the commit if errors occur) were carried out, thus ensuring that the code must be checked before committing.

End of the article, sharing is not easy, praise attention, Ali ga more! (^ – ^)