Front-end popular science series (5): ESLint-Hold the elegant moat

Author: Morrain

Front-end popular science series (5): ESLint-Hold the elegant moat

[Front-end popular science series] To help readers understand the web front-end, it mainly covers the basic knowledge of the web front-end, but does not explain it in depth. It is positioned as large but not detailed and precise. Students who are suitable for non-front-end development have a systematic understanding of the front-end. Better collaboration with front-end development. Write as popular science articles as possible. For front-end development, it is only suitable for novices who are just getting started.

This article is the fifth chapter. It mainly talks about ESLint, a very important tool in front-end engineering. It mainly introduces the history and usage of ESLint and how to build an elegant moat to protect code warehouses based on ESLint.

I. Introduction

During the Warring States Period, the powerful State of Zhao wanted to attack and annex the kingdom of Yan in the north in one fell swoop, while the small country "Liangcheng" is located between the two countries, which is a strategic point and must be taken. So the State of Zhao dispatched generals to flood the lane and led an army of 100,000 to attack the "Liangcheng" with only 4,000 people. The king of Liangcheng asked for help from the Mohist school, who was known for defending the city. But what Liang Cheng waited for was a shameless Mohist knight Ge Li, who was alone in the fight. He was resourceful and resourceful, commanding Liang Cheng's four thousand soldiers and civilians to resist the 100,000 Zhao army and retreat.

Front-end popular science series (5): ESLint-Hold the elegant moat

(Image source: Internet)

"Liangcheng" is like our project warehouse. The order of "Liangcheng" depends on whether "Geli" keeps it! What about our project warehouse? Would you like to see the chaos, no rules, and chaos in the city, or would you like to see the city in order, unified style, and order? How to become the "Geli" among programmers and guard our Sky City?

Front-end popular science series (5): ESLint-Hold the elegant moat

2. About ESLint

1. What is ESLint

In its first look at the official website of definitions on:

Find and fix problems in your JavaScript code

Just one sentence, find and fix the problem in your JavaScript code!

ESLint was originally an open source project created by Nicholas C. Zakas in June 2013. Its goal is to provide a plug-in JavaScript code detection tool.

So why do you need JavaScript code inspection tools? Let's start with the language features of JavaScript.

2. The evolution history of lint tools

In the early development of the C language, there were many non-portable codes in the source program, but they could not be recognized by the compiler. Therefore, Steve Johnson of Bell Labs developed a static code analysis tool on the basis of PCC (PortableC Compiler) in 1979. To scan the C source files and warn about the non-portable code in the source program, this tool was named lint, so subsequent similar tools for checking code are called xxLint.

We talked about the history of the JavaScript language in " Front-end Popular Science Series (1): A Brief History of the Front-End ". It was mentioned that JavaScript was a web scripting language developed by Brendan Eich, a programmer hired by Netscape, in April 1995. The purpose is Embed it in a web page and do some simple verification before submitting.

It took Brendan Eich only 10 days to design and complete the first version of this language. It is estimated that the author never thought that the language JavaScript would develop to the point where it is today, so there were many unreasonable places in the original design. .

Therefore, code verification tools are needed to analyze improper use, and JSlint came into being. In the evolution history of JavaScript language lint tools, there are three milestone tools: JSLint, JSHint and ESLint.

(1) JSLint, the founder of the mountain

In 2008, a very famous book "The Essence of JavaScript Language" was published. Because the cover picture was a butterfly, it was commonly called "Butterfly Book". A very thin book, a must-read book suitable for all introductory JavaScript and must be read many times. The author of this book is Douglas Crockford.

Front-end popular science series (5): ESLint-Hold the elegant moat

It can be seen from the title of "The Essence of JavaScript Language" that the whole book lists all the beautiful features of the JavaScript language. At the same time, at the end of the book, the author also unceremoniously enumerates the dregs and tastes of JavaScript. It can be seen from the style of writing that Douglas is a person who cannot tolerate flaws. So at the end of the book, he also introduced the JSLint tool developed by the author in 2002. Douglas defines all the rules of JSLint. The grammar of dross is strictly prohibited. Yes, if you want to use JSLint, you must accept all its rules.

(2) Carry on JSHint

On December 20, 2011, Anton Kovalyov published a landmark article " Why I forked JSLint to JSHint ", which pointed out several major problems with JSLint:

  • Disturbingly stubborn, did not provide some rules configuration
  • Not paying attention to community feedback

Front-end popular science series (5): ESLint-Hold the elegant moat

So JSHint was born. On the basis of JSLint, with the joint efforts of community developers, the following features were added:

  • More configurable rules, this is the core demand of the community
  • Code modularity
  • Command line tool support, very well integrated with various IDEs

Many advantages make it a necessity for JSLint to quickly replace JSHint.

(3) Restart ESLint

JSLint is inherited from JSHint, so JSLint Top Down Operator Precedence (top-down operator precedence) technology is used to achieve source code parsing, but the huge demand brought by the explosive growth of the front-end makes JSHint more difficult to deal with It is undoubtedly a good way to support third-party plug-ins by exposing AST information.

AST: Abstract Syntax Tree

Front-end popular science series (5): ESLint-Hold the elegant moat

So Nicholas C. Zakas, the author of "JavaScript Advanced Programming", created ESLint in June 2013. ESLint parses the source code into AST, and then checks the AST to determine whether the code conforms to the rules, laying a solid foundation for the high scalability of ESLint basis. ESLint keeps the kernel simple enough, with only 100 lines of code, and the implementation of the rules is completely separated from the kernel.

However, ESLint did not have a big fire at that time, because the source code needs to be converted to AST, the running speed was lost to JSHint, and JSHint already had a complete ecology (editor support) at that time. ESLint really made the fire because of the emergence of ES6.

Refer to the related content of ES6 in " Front-end Popular Science Series (1): A Brief History of Front-end ".

After ES6 was released, JSHint was unable to provide support in the short term due to the addition of many new syntaxes, and ESLint only needed a suitable parser to be able to perform lint checks. At this time, Babel provided support for ESLint and developed babel-eslint, making ESLint the fastest lint tool that supports ES6 syntax.

3. How to use ESLint

After understanding the historical significance and development process of the ESLint tool, let's see how to use ESLint?

1. Install ESLint on the project

Prerequisite: Node.js (>=6.14), npm version 3+.

// 新建demo工程目录,初始化 npm 项目
npm init

// 安装 eslint    推荐安装为项目的开发依赖
npm i -D eslint

// 初始化 eslint 配置文件    因为不是安装到全局的,所以不能直接使用 eslint --init
./node_modules/.bin/eslint --init

During the initialization process, you will be asked to choose some configurations, such as how to use ESLint? We choose the third item with the most features.

Front-end popular science series (5): ESLint-Hold the elegant moat

After selecting the ESLint usage configuration one by one, the .eslintrc.js configuration file will be generated in the project root directory, and the required npm packages will be installed. The npm packages installed in the demo are: eslint-config-standard, eslint-plugin-import, eslint-plugin-node, eslint-plugin-promise, eslint-plugin-standard

The choices in the demo are as follows:

Front-end popular science series (5): ESLint-Hold the elegant moat

After initialization, the generated configuration content is shown below. The meaning of specific configuration items will be discussed later.

// .eslintrc.js
module.exports = {
  env: {
    es2020: true,
    node: true
  },
  extends: [
    'standard'
  ],
  parserOptions: {
    ecmaVersion: 11,
    sourceType: 'module'
  },
  rules: {
  }
}

What needs to be emphasized is that when choosing a code style, I chose the more popular standard specification.

Next we can use ESLint to check and fix the code. First, in the demo project, create a new src directory and create a new index.js file with the following content:

// src/index.js
let a = 10;
let b = 15;
let sum = a + d;
console.log(sum);

At the same time, in package.json, add eslint command eslint src/** to check all files in the src directory.

//package.json
"scripts": {
  "eslint": "eslint src/**"
}

The results of executing npm run eslint in the demo directory are as follows:

Front-end popular science series (5): ESLint-Hold the elegant moat

It can be seen that so many errors have been checked out. Among them,'let must be replaced with const','cannot use title', etc. belong to the rules specified in the standard specification. In addition to style, it also checked out'undefined variables', etc. Syntax error, and give tips one by one.

What should I do if I want to automatically fix the detected problems? eslint supports the use of the --fix parameter. Modify the eslint command in package.json to eslint src/** --fix

Execute npm run eslint again and the results are as follows:

Front-end popular science series (5): ESLint-Hold the elegant moat

Open the src/index.js file and find that the content has changed:

// src/index.js
const a = 10
const b = 15
const sum = a + d
console.log(sum)

As you can see, ESLint automatically fixes the style issues that can be repaired, and at the same time gives tips for issues that cannot be automatically repaired.

For more eslint cli configuration parameters, please refer to the detailed introduction of cli on the official website .

Here we have'dug the moat', but there is no water in the river, and the enemy can still go unimpeded if they want to come over. It is completely dependent on the developer to consciously manually run npm run eslint to complete it. How can we make the "moat" really work? Let's take a look at the common configuration meanings of ESLint, and then introduce in detail how to hold the elegant moat.

2. Common configuration rules

Just after initialization, the .eslintrc.js file was generated in the project root directory, where all eslint configuration items are stored.

module.exports = {
  env: {
    es2020: true,
    node: true
  },
  extends: [
    'standard'
  ],
  parserOptions: {
    ecmaVersion: 11,
    sourceType: 'module'
  },
  rules: {

  }
}

(1) Environment and global variables

The env configuration in the demo defines a set of predefined global variables for the corresponding environment. From the previous examples, we have seen that ESLint will detect undefined variables and report errors, but some are global variables provided by the operating environment or framework, such as $ provided by jQuery. At this time, there are several solutions:

  • In your JavaScript source file, use comments to specify global variables in the following format:
/* global $ */

const dom = $('id')
  • Configure global variables in the configuration file, and set the globals configuration property to an object that contains every global variable you want to use. For each global variable, set the corresponding key value to "writable" to allow the variable to be rewritten, or "readonly" to not allow the variable to be rewritten. E.g:
{
    "globals": {
        "$": "readonly"
    }
}
  • Use env configuration. In order to avoid the trouble of configuring each global variable one by one in the above two solutions, ESLint presets a lot of environment global variable collections. For example, if we want to use the global variables provided by jQuery, we just need to add jquery:true to the env configuration. .

The configuration of env in the demo, es2020:true means adding es2020 syntax features, node:true means adding all global variables in node. For more environments, please refer to the  relevant chapters of the designated environment on the official website  .

(2) Expansion

In .eslintrc.js, rules are used to configure ESLint rules. For the specific method of configuring rules, please refer to how to configure rules on the official website   and  the description of all rules. I will not introduce them in detail here. Also for convenience, ESLint uses extends configuration to take effect at one time. A set of rules. For example, no rules are configured in the rules in the demo, because a set of rules conforming to the standard specification is configured through extends.

ESLint supports three types of extensions:

  • ESLint official extension beginning with eslint:'.

    Including eslint:recommended and eslint:all, where eslint:recommended is a recommended set of rules, and eslint:all is all the rules in ESLint and is not recommended because it may be changed by ESLint at any time.

  • Shared extension.

    Provide a set of shared configuration through the npm package. The package name prefix must be eslint-config-, and the extension attribute value can omit the package name prefix eslint-config-. Stanard in the demo corresponds to a set of rules provided by the package'eslint-config-standard' in package.json.

  • The extension provided in the plugin.

    When the demo is initialized, we can see that plugin packages such as eslint-plugin-node are installed. These plugin packages are dependent on eslint-config-standard, so they will be installed automatically. These plugin packages also provide some rules for extension.

For example, the following code is wrong in the node module and should be written as module.exports. If you want ESLint to be able to detect this error, you need to add the rules provided in the eslint-plugin-node package to the extension.

// src/index.js
  exports = {
    foo: 1
  }

  // .eslintrc.js
  extends: [
    'standard',
    'plugin:node/recommended'
  ]

Since eslint-plugin-node has been installed by default, it does not need to be installed separately. For plug-in packages that are not installed, if you want to use the rules provided by it, you need to manually install this plug-in package.

(3) Plug-in

When talking about extensions above, I have already mentioned how to load the extension configuration in the plugin. Now that there are so many extensions available, why do you need plugins? Because ESLint can only check standard JavaScript syntax, if you use Vue single-file components, ESLint will be at a loss. At this time, the corresponding framework will provide supporting plug-ins to customize specific rules for inspection. Similar to extensions, plugins also have a fixed prefix eslint-plugin-, which can also be omitted during configuration.

We added a new single-file component of Vue as follows. After executing npm run eslint, we found that it had no effect and could not check for errors in .vue. At this time, we need to install the eslint-plugin-vue plugin.

// src/index.vue
<script>
let a = 10
const b = 15
const sum = a + d
console.log(sum)
</script>
npm i -D eslint-plugin-vue

There are two ways to configure the plug-in in .eslintrc.js after installation :

  • Configure via plugins
module.exports = {
    plugins: ['vue']
}

After the configuration is completed and executed npm run eslint, it is found that the src/index.vue file is not checked. The original plugins: ['vue'] just declares the rules provided by eslint-plugin-vue that you want to reference, but which ones to use and how to use them are still needed Configure one by one in the rules. So generally we use the second way to configure plugins.

  • Through the extends configuration, the above-mentioned configuration extension method.
module.exports = {
  extends: ['plugin:vue/recommended']
}

In this way, both the plugin is loaded and the rules provided by the plugin are specified, and the code on the vue file has been successfully checked, as shown in the following figure:

Front-end popular science series (5): ESLint-Hold the elegant moat

(4) Parser and its configuration

module.exports = {
  parserOptions: {
    ecmaVersion: 11,
    sourceType: 'module'
  }
}

The parserOptions in the demo is the parser configuration. ESLint only supports ES5 grammar by default, but the supported ES version can be set through the parser configuration. For example, ecmaVersion:11 in the demo indicates that the grammar of ES11 (ie ES2020) is supported. Note here It is through the parser configuration that only supports the grammar. For the newly added global variables of this version, the support is still completed through the env configuration. For related instructions and more parser configurations, please refer to the official website to  specify the parser configuration .

ESLint uses ESPree as its parser by default , but you can also specify a different parser through the parser field. You can refer to the official website to  specify a parser .

So why do you need to specify a parser? Because ESLint's default parser only supports grammatical features that have formed the ES standard, for experimental and non-standard (such as Flow, TypeScript, etc.) that need to use Babel-transformed grammar, you need to specify the @babel/eslint- provided by Babel. parser. This shows that under normal circumstances, there is no need to specify a third-party parser.

Take @babel/eslint-parser as an example. After specifying it as the parser of ESLint, the source code we developed is first configured by @babel/eslint-parser according to the configuration of Babel (refer to " Front-end Popular Science Series (4): Babel—— ES6 sent to heaven ") Convert the source code to the AST supported by ESLint by default, and keep the number of ranks of the source code to facilitate the output of the wrong location. It’s not enough to specify @babel/eslint-parser. The role of the parser is only to convert the grammatical features that ESLint can’t recognize into ESLint, but it doesn’t include rules and needs to be provided by @babel/eslint-plugin Corresponding rules can perform ESLint's code detection normally.

For more details, please refer to the  official documentation of @babel/eslint-parser .

So far, the common configuration has been introduced. For more configuration introduction, please refer to ESLint official website document  configuration ESLint .

Fourth, how to hold the elegant moat

As mentioned earlier, so far, we have just dug the moat, but there is no water in the river, and the enemy can still go unimpeded if they want to come over. Source code detection is completely dependent on the developer consciously manually running npm run eslint to complete, then how can we make the "moat" really work?

1. Enjoy the fun of development

The first requirement is that it is better to do code inspection during the development process , instead of running npm run eslint to see the error after the code development is completed. At this time, there may be a lot of errors.

Take the VS Code editor as an example (other editors should have similar plugins), install the ESLint extension plugin  . The editor plug-in will read the configuration of .eslintrc.js in the current project, and prompt the error that does not meet the rules in the editor.

Front-end popular science series (5): ESLint-Hold the elegant moat

First of all, you can see that the file in question turns red on the directory tree, click on this file, there will be an error message on the corresponding line, and the mouse will show an error message for easy repair. But sharp-eyed students may have discovered that running npm run eslint not only detects errors in index.js, but also detects errors in index.vue. There are 7 errors in total. The editor only detects errors in index.js.

It turns out that the ESLint plugin of the editor can only detect .js files by default. You need to adjust the settings of the editor ESLint plugin to allow it to support the detection of .vue files.

Front-end popular science series (5): ESLint-Hold the elegant moat

As shown in FIG:

  • Find the plug-in settings entry.
  • Because the added support for vue files is for projects, not all projects are vue projects, so we take the settings into the workspace.
  • Add vue to the Validata configuration.

Front-end popular science series (5): ESLint-Hold the elegant moat

Front-end popular science series (5): ESLint-Hold the elegant moat

As you can see, the index.vue file has also turned red, the errors inside can also be detected, and all 7 errors of the project can also be displayed in the "Question" column of the editor, which has the same effect as running npm run eslint.

In this way, there will be error prompts during development, just modify according to the prompts, but we mentioned earlier that running npm run eslint can automatically fix the problems that can be repaired through the --fix parameter, such as format problems, change let to const Wait for these questions.

Can the detected errors be automatically repaired during development?

Three options , you can choose according to your preference:

  • The settings are automatically restored when they are saved.

Front-end popular science series (5): ESLint-Hold the elegant moat

  • Bring up the command panel of the VS Code editor and find the repair command provided by the ESLint plugin.

Front-end popular science series (5): ESLint-Hold the elegant moat

  • Set the repair command provided by the ESLint plug-in to your favorite shortcut, and use the shortcut to repair.

At this point, we found that the automatic repair is only effective for the index.js file. Similarly, the ESLint plug-in must be configured to support the automatic repair function of Vue files.

Front-end popular science series (5): ESLint-Hold the elegant moat

2. Carry the fun to the end

Now we have been able to detect errors during development and make it easier for developers to fix problems in time, but this depends on the consciousness of the development students. If the development students do not consciously or forget, the code submitted at this time will still submit the wrong code to Go to the warehouse. At this point, we need to use husky to intercept the git operation and perform a code check before the git operation.

Front-end popular science series (5): ESLint-Hold the elegant moat

(Image source: Internet)

  • Install and configure husky
npm i -D husky
// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "eslint src/** --fix"
    }
  }
}

Front-end popular science series (5): ESLint-Hold the elegant moat

At this time, all files under src will be checked before submission. Since the source code in the demo is problematic and the ESLint check fails, it cannot be submitted now, which prevents the development from forgetting to fix the problem detected by ESLint.

For old projects, there may have been many legacy style issues, which caused the ESLint check to fail. At this time, it is impossible to fix all the problems one by one. Blocking submissions altogether will inevitably have an impact. In addition, for a single submission, it is unnecessary to check all files under src every time. So we need to use the lint-staged tool to detect only the currently modified part.

  • Install and configure lint-staged
npm i -D lint-staged
// package.json
{
    "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,vue}": [
      "eslint --fix",
      "git add"
    ]
  }
}

For specific configuration, please refer to the  lint-staged  official website document. The configuration in the example means that the currently changed .js and .vue files are detected and automatically repaired when they are submitted. After the automatic repair is completed, add to the git temporary storage area. If there are errors that cannot be repaired, an error message will be reported.

3. Install the "black box"

The aircraft is equipped with black boxes. When a malfunction occurs, it is convenient to go back to the voyage record and find the problem. Our code warehouse is the same, every submission should be recorded. However, the information entered by each developer when submitting is different, and there is no uniform format, which leads to dazzling and inefficient submission of records later.

Next, let's look at how to constrain submissions to keep the gate of elegant submission logs.

Front-end popular science series (5): ESLint-Hold the elegant moat

commitizen is a tool used to format git commit message, which provides an inquiry-style way to obtain the required commit information.

The cz-conventional-changelog is used to specify what information needs to be entered when submitting, such as the type of submission is to fix the problem or function development, the scope of the submission, etc., cz-conventional-changelog is the rule provided by the official website, which can be completely based on the actual situation of the project Self-developed suitable rules.

After standard-version submits information and constrains, the submitted log information will be more unified. Using standard-version, it is easy to automatically generate the submitted log CHANGELOG file.

  • Install and configure
npm i -D commitizen cz-conventional-changelog standard-version
//package.json
{
  "scripts": {
    "c": "git-cz",
    "version": "standard-version"
  },
  "standard-version": {
    "changelogHeader": "# Changelog\n\n所有项目的变更记录会记录在如下文件.\n",
    "dryRun": true
  },
  "config": {
    "commitizen": {
      "path": "cz-conventional-changelog"
    }
  }
}

After the configuration is completed, use npm run c to submit the modification, and the interactive prompt as shown in the following figure will be displayed. Just fill in the corresponding content according to the rules.

Front-end popular science series (5): ESLint-Hold the elegant moat

Submitted in this way, the submitted log is in a unified format, and then npm run version is used to generate the CHANGELOG file.

standard-version will automatically bump the version number of the project, and generate a commit log file between the two versions, and then upload it to the warehouse with a version tag. For more information about standard-version functions, please refer to the official website document standard-version .

Front-end popular science series (5): ESLint-Hold the elegant moat

4. The last line of defense

Now if you use npm run c to submit changes in development, everything will be great, but if you forget to use npm run c to submit changes, what should you do if you use git commands or other tools to submit changes? How to guard the last line of defense?

The answer is to verify the submitted information when submitting. If it does not meet the requirements, it will not be submitted and a prompt will be given. The verification is done by commitlint , and the timing of verification is specified by husky . Husky inherits all hooks under Git. When the hook is triggered, Husky can prevent illegal commit, push, etc.

  • Install and configure
// 安装工具包
npm install --save-dev @commitlint/{config-conventional,cli}

// 生成 commitlint 配置文件
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js

@commitlint/cli is used to perform the inspection, @commitlint/config-conventional is the inspection standard, that is, whether the submitted information meets the requirements of this standard, and only if it meets the requirements, the submission is allowed.

Generate the configuration file, specify the specifications to be used, and add the'commit-msg' hook in husky. After the configuration is complete, any submissions made through non-npm run c channels will be intercepted and an error will be reported.

// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }
}
  • Verification at the time of wrong submission

Front-end popular science series (5): ESLint-Hold the elegant moat

Five, summary

Based on ESLint, we have successfully transformed into the "Geli" of the programmers world, guarding our battlefield, and letting our sky city be clean, pure, uniform, and soar in elegance!

Six, references

  1. Deep understanding of ESLint
  2. ESLint official website
  3. JS Linter evolution history
  4. Discussion on the working principle of ESLint
  5. Books: "The Essentials of JavaScript Language"

Guess you like

Origin blog.51cto.com/14291117/2544584