It is very necessary for the front-end team to ensure the consistency of code quality and code style in the process of collaboration. Using Lint checks (such as Eslint, etc.) to standardize code is currently the more common approach. To ensure that all code in the repository passes Lint checks, we need to have every developer force a Lint check on submitted code before submitting it. If it doesn’t pass Lint checks, the code will fail.

In this article, we will introduce a practical way to automatically install and enforce multiple Lint checks in a Node.js project, using Git’s pre-commit hook and build commands in the dev environment. The directory structure is as follows:

  • Introduction and configuration of Lint checking
  • Lint checks the hook implementation
    1. Git Hooks to introduce
    2. Check the implementation of the script
  • Complete the automatic installation of Lint checks through the Gulp task

Introduction and configuration of Lint checking

Lint checking refers to specifying the specification that code is written from a configuration file and checking that the code conforms to the configured specification by running the corresponding program. There are different mainstream Lint checkers for different types of files.

The inspectors for file types used in this article’s practice project are: *.js → ESLint *.scSS → stylelint *.ts & *.tsx → TSLint

Using ESLint as an example, the configuration process is as follows:

  • Add the inspector you want to use to your project (ESLint example) :

    npm install eslint --save-dev
  • Add the inspector configuration file (for example, ESLint) to the project: see the instructions on the official website
  • To check ESLint for a file, run the following command on the command line:

    // ESLint needs to be installed globally

    eslint xxx.js

    // ESLint is not installed globally, using dependencies installed in the project directly)

    ${relative path}/node_modules/.bin/eslint xxx.js
  • If the detection does not conform to the configured specifications, the command line will display similar error output:

Lint checks the hook implementation

1. Introduction to Git Hooks

A Hook is a custom script that is triggered when a specific action occurs. Most version control tools provide Hook extensions, and Git is no exception. Git Hooks: pre-commit, prepare-commit-msg, commit-msg, post-commit. The server side is the operation flow-related hook that the network request occurs on, such as the operation flow-related hook that is pushed to a remote one.

Git Hook can be found on the official website

The new Git repository will provide you with examples of Hooks with.sample extensions. Remove the.sample suffix and they become real Hooks that will be executed at certain times.

This article uses the pre-commit hook, which occurs before the COMMIT operation completes. If the script returns a non-zero value, the COMMIT operation will not take place.

2. Check the script implementation

As mentioned above, we need to store the pre-commit hook script in the project /.git/hooks, which will be executed automatically when the user enters the commit command. There are also three js scripts checked by Lint that will be called and executed in the pre-commit script. The directory structure is as follows:

.git ├── antigene-├ ─ antigene-├ ─ antigene-├ ─ antigene-exercises ─ antigene-exercises ─ antigene-exercises ─ antigene-exercises ─ antigene-exercises ─ antigene-exercisesCopy the code

The pre-commit script is as follows: /.git/hooks/pre-commit

#! /bin/sh # $? If the return code of the previous instruction is 0, proceed to the next lint check # Otherwise exit with 1, terminating the commit operation if [$? -eq 0]; then node "./.git/hooks/eslint-hook.js" else exit 1 fi if [ $? -eq 0 ]; then node "./.git/hooks/stylelint-hook.js" else exit 1 fi if [ $? -eq 0 ]; then node "./.git/hooks/tslint-hook.js" else exit 1 fiCopy the code

The script executes three similar code blocks, each of which checks if the previous block’s Lint returns a non-zero value. If so, exit 1 will exit the script process and terminate the COMMIT operation. Otherwise, node “./git/hooks/xxx.js” will be executed, which is where Lint, also placed under.git/hooks, checks for js scripts. Because it is a Node.js project, the default development environment is node.js environment, so through Node to execute JS scripts, to complete the three file types of Lint check.

/.git/hooks/eslint-hook. Js: /.git/hooks/eslint-hook

#! /usr/bin/node const childProcess = require('child_process'); const path = require('path'); Const cmdStr = 'git diff-index --cached HEAD --name-only --diff-filter=ACMR -- *.js'; const files = childProcess.execSync(cmdStr).toString().replace(/[\r|\n]/g, ' '); // Exit with 0 if (! files) { process.exit(0); Const MAX_FILE_LENGTH = 7900; const MAX_FILE_LENGTH = 7900; const fileChunks = []; let tmp = files; while (tmp.length > MAX_FILE_LENGTH) { let spliceIndex = MAX_FILE_LENGTH; while (spliceIndex >= 0) { if (tmp[spliceIndex] === ' ') { break; } spliceIndex--; } if (spliceIndex === 0) { console.log('eslint error: file name too long'); process.exit(1); } fileChunks.push(tmp.slice(0, spliceIndex)); tmp = tmp.slice(spliceIndex + 1); } fileChunks.push(tmp); const promises = fileChunks.map((fileChunk) => { return new Promise((resolve, Reject) => {// Find the esLint binary under node_modules in the project // Run eslint on the changed file path const CMD = ` ${path. The normalize (' ${relative path} / node_modules/bin/eslint ')} ${fileChunk} - color `; childProcess.exec(cmd, {maxBuffer: 100 * 1024 * 1024}, (err, stdio, stderr) => {if (err) {// Prints error console.log('eslint error:'); console.log(stdio || err); reject(stdio || err); } resolve(); }); }); }); Promise.all(promises).then(() => {// If there is no error, exit with 0; }, (error) => {// There is an error, exit process.exit(1); });Copy the code

Git diff command is used to obtain a list of file paths of a certain type. Then use the corresponding Lint in node_modules of the project to check the execution file and run the Lint check command on the file path. Exit with 0 if it passes the check; exit with 1 otherwise.

At this point, as long as the Node.js project has the relevant Lint checking dependencies installed and the above pre-commit script and Lint checking JS script are correctly stored in the.git/hooks/ path, the developer is done enforcing Lint checking.

Complete the automatic installation of Lint checks through the Gulp task

Because the.git folder is not included in the Git repository, there is no way to synchronize the repository so that all developers on the project have pre-commit checks installed locally. Obviously, it’s not a very scientific approach for every developer to manually copy scripts to their local directories. So how do you automate the installation of Lint checking scripts?

Node.js projects typically perform build tasks or start local servers (such as in combination with engineering tools such as Webpack or Gulp) while developing in a local dev environment. In the project described in this article, we used the Gulp build tool, so we can add a task to install Lint checking scripts to the locally developed build process to complete the automatic installation of Lint checking.

Automatic installation is a simple way to put the previously described Lint checking scripts in the repository and copy them to the.git/hooks/ directory of your project via the installation script. This enables multi-developer projects, combined with repository synchronization and local development processes, to automatically install Lint checking execution scripts in each developer’s local environment, thus forcing Lint checking to be completed when each developer commits.





Creative Commons Attribution – Non-commercial Use – Same way Share 4.0 International License