Necessary for front end interview — eslint and git hook


Necessary for front end interview -- eslint and git hook


At the end of eslint, I gave the code of configuring eslint and git hook to Vue cli, but I guess you still have a lot of questions in your heart, such as why to match, how to customize the configuration, and why the configuration can’t take effect. Don’t worry, after reading this article, I guess you will really know it.

Brief introduction of GIT hook

1. What is it

Like other version control systems, GIT can trigger custom scripts when certain important actions occur. There are two sets of such hooks: client-side and server-side. The client hook is called by operations such as commit and merge, while the server hook is used for networking operations such as receiving pushed commit.

2. Why

Using these hooks at will can increase our control over the program and realize more functions.

3. Usage

In the current project. Git / hooks, there are many hook. Sample files. Here we only talk about the pre commit hook

The pre commit hook runs before typing the commit information. It is used to check the snapshot to be submitted, for example,Check for omissions, ensure test runs, and verify code。 If the hook exits with a non-zero value, GIT discards the commit

The hook will take effect when you remove. Simple and then git commit

4. Write a git hook script

Delete the content of pre commit. We can write scripts through shell programming.

//Pre commit file
Echo "execute script before git commit"

Enter git commit in the console, and we can see that the console prints this sentence
So far, we have completed the simplest hook script

Eslint and git hook

1. Engineering

In the development team, in order to keep the hooks used by the team consistent, maintenance is relatively complex, because. Git / hooks directory is not copied with your project, and is not affected by version control.
The simple solution is to store the hook files in the actual directory of the project (outside. GIT), so that version control can be carried out just like other files, and then create a link in. Git / hooks, or simply copy them to the. Git / hooks directory after updating.

The specific method is to create a pre commit executable file in the root directory and configure NPM script
"hooks": "copy /y .\\.git_hooks\\*.* .\\.git\\hooks\\"
After NPM install week, NPM run hooks can complete the above operation

2. Write hook script directly

Before we write is the simplest script, understand the principle of writing script
Now let’s write a pre commit (eslint) script that can use the actual environment
Color part of you can see this article, although he wrote the wrong place, the system default color



#Variables that define colors
RED_ COLOR='\x1b[31; 4m '# red

GREEN_ COLOR='\x1b[32; 4m '# green
YELLOW_ COLOR='\x1b[33; 4m 'yellow
BLUE_ COLOR='\x1b[34; 4m '# blue
PINK='\x1b[1; 35; 4m '# Pink
LIGHT_ BLUE='\x1b[1; 36; 4m '# sky blue
WHITE='\x1b[1; 37; 4m '# sky blue
#I really can't understand the following line. It must have something to do with git add commit file. If you are interested, you can study it
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".\(js\|vue\)$" | grep -v "node_modules" | grep -v "static")
#No file submitted, exit
if [[ "$STAGED_FILES" = "" ]]; then
  exit 0


echo  "\nValidating Javascript:\n"
#Here we use variables instead of special characters, so we don't need echo - E
# Check for eslint
which eslint &> /dev/null
if [[ "$?" == 1 ]]; then
  echo  "${RED_COLOR}Please install ESlint${RES}"
  exit 1

#Get each file to execute eslint
  eslint "$FILE"

  if [[ "$?" == 0 ]]; then
    echo  "\t${GREEN_COLOR}ESLint Passed: $FILE${RES}"
    echo  "${RED_COLOR}ESLint Failed: $FILE${RES}"

if ! $PASS; then
  echo  "${RED_ Color} commit failed: ${res} eslint check failed. Please fix the eslint error and try again“
  exit 1
# $?  Is the last execution result
exit $?

3. Through pre commit

The above one is used in our project. It’s real and can run. It’s written by our boss. It’s shell programming.
But I don’t think the front end of the dish chicken is so high-end. How can I fix it
No fear, pre-commit can automatically call our NPM run test before git commit (which can be specified).

pre-commit is a pre-commit hook installer for git. It will ensure that your npm test (or other specified scripts) passes before you can commit your changes. This all conveniently configured in your package.json.

"scripts": {
    "test": "echo \"Error: I SHOULD FAIL LOLOLOLOLOL \" && exit 1",
    "foo": "echo \"fooo\" && exit 0",
    "bar": "echo \"bar\" && exit 1"
  "pre-commit": [
    "Bar", // stop when 1 is encountered

After installation, you can configure it according to the above. It should normally execute foo – > and then return 1 when executing bar, report an error and stop
In fact, with this tool, we no longer have to write boring shell scripts
Smart you probably have come up with it. You can directly execute the configured lint script as described in the previous article

"scripts": {
    "lint": "eslint --ext .js .jsx .vue src"
  "pre-commit": [
    "Lint" // Mark 1

If the eslint check does not pass and returns 1, the program will stop at Mark 1 and foo will not be executed

4. Optimize with lint stage

In fact, the above configuration can meet the absolute requirements, but smart you find that every time you lint, it is the SRC folder of lint, but we only want the problem of lint submission. At this time, we need to ask another library, lint stage, which only helps us to process the files in Git stage (that is, the files in Git add each time)

Linting makes more sense when run before committing your code. By doing so you can ensure no errors go into the repository and enforce code style. But running a lint process on a whole project is slow and linting results can be irrelevant. Ultimately you only want to lint files that will be committed.

This paper summarizes the standard writing methods in the document, including the following business writing methods
Note that I have not verified whether adding Husky is useful, because my project is in Vue cli, so Husky is not needed

  "scripts": {
    "lint": "eslint --fix --ext .js .jsx .vue src"
    "lint-staged": "lint-staged"
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
  "lint-staged": {
    "*. {JS, JSX, Vue}": ["NPM run lint", "git add"] // tag 2

Let's talk about why git add is added to mark 2. This is because we add a parameter after selint -- fix will automatically repair the file. The repaired file belongs to the newly generated file. We automatically add git add to staged

5. Configuration under Vue cli

The official document of Vue cli is

  "gitHooks": {
    "pre-commit": "lint-staged"

But I found that this writing method is wrong. If there is a githooks attribute, Vue will always execute the test script and report an error.

The following writing method is being used in my project. It must be no problem. Please feel free to copy it

 "scripts": {
    "dev": "vue-cli-service serve",
    "build": "vue-cli-service build ",
    "test": "vue-cli-service build --mode productionTest",
    "lint": "vue-cli-service lint --fix --quiet",
    "lint-staged": "lint-staged"
  "pre-commit": "lint-staged",
  "lint-staged": {
    "*.{js,jsx,vue}": ["npm run lint","git add"]

I don’t know why in another multi page project, all JS, Vue and JSX files in SRC are detected every time. And — fix doesn’t work,It can also be repaired automaticallyI don’t know why, but I made a mistake? Damn, it’s hard to understand
For the time being, the following configuration will be used for multiple pages, and the file range will be added manually after lint
“scripts”: {

"dev": "vue-cli-service serve --inline --progress ",
"build": "vue-cli-service build && node src/utils/copy.js",
"buildTest": "vue-cli-service build --mode productionTest && node src/utils/copy.js",
"buildLocalTest": "vue-cli-service build --mode productionLocalTest && node src/utils/copy.js",
"lint": "vue-cli-service lint --fix --quiet src/module/toutiaoSearch/",
"lint-staged": "lint-staged"

“pre-commit”: “lint-staged”,
“lint-staged”: {

"*.{js,jsx,vue}": [
  "npm run lint",
  "git add"



This paper introduces the relationship between eslint and git hook in detail, hoping to bring help to your project.
I haven’t written an article for a long time. Today, I wrote two articles in one breath. I hope I can sweep away the decadence of the past and cheer up again. Come on!