Front-end code specification tools improve code quality in three ways:

  1. Improve code quality and catch potential bugs such as using unused variable declarations (no-unused-vars) and avoiding no-loss-of-precision;
  2. Uniform code formatting, such as max-len and keyword-spacing;
  3. Prevent non-standard code from entering the code base and standardize the submission of information.

This article will interpret the principle and use of each tool according to its official documents, and give the best practices, so as to know why and how to use it.

eslint

Js is a dynamic, loosely typed language that is prone to errors and needs to be discovered at run time, so Microsoft has introduced typescript as a language to compensate for the inherent shortcomings of JS (learn typescript again in a new way to learn more about TS).

How can we minimize this problem? Eslint is An ast-based pattern checker for JavaScript that statically analyzes code for various custom rules based on abstract syntax trees generated by JS code. Bugs can be found and fixed automatically without execution (dealing with both code quality and code format).

The above sentence basically summarizes the features and working principles of ESLint. The following aspects will provide an in-depth understanding:

  • use
  • configuration
  • Vscode integration

use

Eslint is a NPM package, to use need to install first, and then by executing the command line command code related documents for check and repair, which involved in the process of using some configuration, can be added directly on the command line, also can through the configuration file configuration, here are the use of the principle is in addition to a few on the command line to add, Other parameters are configured in the configuration file.

Node.js version requirements: ^10.12.0, or >=12.0.0.

  1. Installation (Yarn as an example)
yarn add eslint --dev
Copy the code
  1. Initialize the configuration file (NPX can be used directly if the global installation is available, otherwise NPX needs to be added)

Eslint works according to the configuration at runtime.

npx eslint --init
Copy the code

After running this command, you need to customize some configurations based on the options, for example

How would you like to use ESLint? · Style √ What type of modules does your project use? · ESM √ Which framework does your project use? · None √ Does your project use TypeScript? · No/Yes √ Where does your code run? · Browser, Node √ How would you like to define a style for your project? · Guide √ Which style guide do you want to follow? · Standard √ What format do you want your config file to be in? JSON,Copy the code

At this point, a.eslintrc.json configuration file is generated in the project root directory and the dependent installation package is downloaded.

  1. Check and repair

Eslint use the syntax for eslint [options] [file | dir | glob] *, for example

eslint file1.js file2.js
eslint lib/**
Copy the code

Options include:

  • – fix repair
  • -c, –config Specifies another configuration file

configuration

Eslint is designed to be fully configurable, which means you can turn off all rules and leave only basic syntax validation. There are two main ways to configure esLint (not including configuration on the command line) :

  • Configuration Comments: Use Comments as Configuration directly in the file
  • Configuration Files: Use JavaScript, JSON, or YAML Files as the Configuration of the entire directory or sub-directory. For the overall structure, refer to schema

See Configuring ESLint for more details. Here are some of the main configurations

  • ParserOptions: Language options for parsing, including ECMA version, code type (module or script), ECMA features (such as JSX, etc.)
  • Parser: Parser is used to parse JS into AST, Esprima by default, ts or Babel parsers can be used for compatibility
  • Processor: a processor that extracts JS files from other types of files for processing
  • Env: Preset global variables by setting the corresponding environment, such as Browser or Node
  • Globals: custom global variables
  • Plugins: Plugins are a series of NPM packages prefixed by eslint-plugins. Plugins can be used without prefixes. Plugins can also be configured for reuse
  • Rules: specifies specific rules. See the default rules of ESLintRules, you can modify specific rules. The possible values include
    • “Off” or 0 to turn off the rule
    • “Warn” or 1 warning
    • “Error” or 2 indicates an error

Array syntax is used for multiple arguments, as in

The configuration file

{
   "rules": {
       "eqeqeq": "off",
       "curly": "error",
       "quotes": ["error", "double"]
   }
}
Copy the code

/* ESlint quotes: [“error”, “double”], curly: 2 */ Closes the rule

/* eslint-disable */

alert('foo');

/* eslint-enable */
Copy the code

Specify rules for specified rows

alert('foo'); // eslint-disable-line no-alert, quotes, semi
Copy the code
  • Extends extends other configuration files, including those shipped with ESLint (ESLint :recommended, or ESLint: All) or other shareable config, or those shipped with plug-ins
{"plugins": ["react"], "extends": ["eslint:recommended",// esLint comes with a configuration "plugin:react/recommended", "rules": { "react/no-set-state": "off" } }Copy the code
  • IgnorePattern Specifies files to be ignored, for example
{ "ignorePatterns": ["temp.js", "**/vendor/*.js"], "rules": { //... }}Copy the code

You can also use the.eslintignore file, noting the forward slashes (/) delimiter

# Valid
/root/src/*.js

# Invalid
\root\src\*.js
Copy the code
  • Overrides: Overrides rules for a part of a file
{ "rules": {... }, "overrides": [ { "files": ["*-test.js","*.spec.js"], "rules": { "no-unused-expressions": "off" } } ] }Copy the code

Vscode integration

Eslint can be integrated with a variety of editors and tools. This section only introduces VScode integration. You can download the ESLint plugin to implement save-time detection

    "editor.codeActionsOnSave": {
        "source.fixAll": true
    }
Copy the code

prettier

Prettier is a code formatting plug-in that beautifs most of the front-end file code according to certain rules. Prettier does this by converting all formats except Empty Lines and multi-line Objects into AST and regenerating code in a new format according to the configured rules. Prettier concentrates on the format of code rather than the quality of code. Here are three parts:

  • use
  • configuration
  • Vscode integration

use

The installation

yarn add --dev --exact prettier
Copy the code

Create a configuration file to let the editor know we’re using Prettier

echo {}> .prettierrc.json
Copy the code

You can create a file. Prettierignore to indicate which files do not need formatting

# Ignore artifacts:
build
coverage
Copy the code

Format using prettier

npx prettier --write .
Copy the code

Replacing –write with –check simply checks without processing

configuration

“, and unlike esLint’s fine-grained configurability, PertTier offers a small number of configuration options that are slightly less flexible but easier to use. Configuration files are similar to ESLint in that you can refer to schema for structure and Configuration File for other Configuration parameters

Vscode integration

Downloading the prettier plug-in allows you to format files when you save them, but we will use esLint in combination with Prettier later. Running ESLint automatically formats the file, so we won’t talk about it here.

Use esLint and prettier together

After introducing the two tools, let’s combine them first. As mentioned earlier, esLint solves both code quality and format problems, so why prettier? The answer to this question is that ESLint cannot fix certain formatting problems, such as max-len (Why You Should Use esLint, Prettier & EditorConfig), You need to manually modify it. That’s why Prettier vs. Linters noted that EsLint is responsible for code quality, while Prettier is responsible for formatting.

Combining the two needs to solve two problems, one is to quickly execute commands from both tools, and the other is to turn off formatting rules in ESLint to avoid rule conflicts between the two tools. There are two auxiliary packages, eslint-plugin-prettier and eslint-config-prettie What’s the difference between prettier-eslint, eslint-plugin-prettier and eslint-config-prettier? .

Eslint-plugin-prettier is an ESLint plug-in that automatically prettier when esLint is implemented as part of a plug-in, assuming that esLint and Prettier have been downloaded as described in the previous two parts. The installation

yarn add eslint-plugin-prettier  --dev
Copy the code

Add on the ESLint configuration file

{
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}
Copy the code

This solves the problem of running both commands simultaneously. Go ahead and download eslint-config-prettie, which provides the ESLint configuration file that makes all formatting rules in ESLint unavailable.

yarn add eslint-config-prettier --dev
Copy the code

In eslint extends array in the configuration file will be the plugin: prettier/add it to the last

{
  "extends": ["plugin:prettier/recommended"]
}
Copy the code

This solves the problem of format rule conflicts.

Eslint and Prettier lived happily ever after.

githooks

Git provides many hooks that trigger when certain actions occur. For details about gitHooks and Git, see git principles and commands: What happens when you manipulate Git. We introduced gitHooks here primarily to solve two problems

  • Prevent non-standard code from entering the code base
  • Specification submission information

There are two hooks for pre-commit and commit-msg, respectively.

  • There are two ideas to ensure that the code entering the hook pre-commit is normal code
    • In this hook the code is checked for normality, and if not, returns 1, cancels the commit
    • In this hook fix specification, it executes if it has been fixed and conforms to the specificationgit addAdd the fixed code to index, continue commit, otherwise return 1, cancel commit
  • When the hook commit-msg is executed, the committed information is checked, and if it does not meet the criteria, a 1 is returned to cancel the commit.

Let’s edit the hook

Direct edit hook

Git hooks are in the. Git /hooks/ directory of your project, which contains templates for different hook scripts. Edit them (for example, replace them with the following script). Remove the suffix. Sample from the corresponding template, and it will be executed automatically when we submit the project.

  • pre-commit

Run eslint on the file in the staging area and git add to add index again

for file in $(git diff --cached --name-only | grep -E '\.(ts|tsx)$') do echo ":$file" node_modules/.bin/eslint "$file" --fix # if [$? -ne 0]; then echo "ESLint failed on staged file '$file'. Please check your code and try again. You can run ESLint manually via NPM run eslint." exit 1 # exit with failure status\ fi git add "$file" # Add lint code back to index doneCopy the code
  • commi-msg

For example, the number of submitted information cannot be less than 10

#! /bin/sh MSG=`awk '{printf("%s",$0)}' $1` if [ ${#MSG} -lt 10 ] then echo "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --" echo "current the commit message is: $MSG" echo "commit message ${#MSG} "echo "commit message To submit "echo" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "exit 1 fiCopy the code

This does what we want, but the downside is that the scripts here are not synchronized to the remote repository for reuse.

Use third-party tools

This feature has been better implemented, and we’ll introduce three packages next

  • Husky modifies the corresponding hook files according to the configuration to implement hook reuse
  • Lint-staged formatting with Husky, Prettier, ESLint/TSLint, or stylelint for the file to be committed, re-insert index into the formatted file, and continue commit
  • Commitlint and HusKY check the submitted information

Before we start, if we have manually changed the corresponding hook file, we need to remove it, otherwise it will affect the use of Husky.

Download three packages

yarn add husky lint-staged --dev
yarn add @commitlint/{cli,config-conventional} --dev
Copy the code

Create a Commitlint configuration file that specifies that the Commit is validated against config-Conventional, which complies with Angular Commit Guidelines.

echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js
Copy the code

Modify package.json configurations as follows

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*.js": "eslint --fix"
  }
Copy the code

Where the husky field is the husky configuration, which can contain various gitHooks, we only use two of them here:

Lint-staged fields, which can be modified as necessary, are called when pre-commit, and this demo means esLint –fix for all files with the JS suffix

Commitlint -e HUSKY_GIT_PARAMS, where -e refers to the file where the commit information is stored, Git /COMMIT_EDITMSG,HUSKY_GIT_PARAMS is a parameter that husky passes to commitlint about the commit.

conclusion

We now have practical solutions to all three of our code specification problems. While common scaffold like vue-CLI or create-React have tools built in, you need to understand why they work in principle before you can tweak them or even build your own scaffolding.

This paper combs and interprets the tools involved in the three functions. Some details need to be improved, and this content will be further optimized and updated in the future.

reference

  • Take a new look at typescript
  • eslint
  • prettier
  • Why You Should Use ESLint, Prettier & EditorConfig
  • eslint-plugin-prettier
  • eslint-config-prettie
  • What’s the difference between prettier-eslint, eslint-plugin-prettier and eslint-config-prettier?
  • What happens when you manipulate Git
  • husky
  • lint-staged
  • commitlint
  • config-conventional
  • Angular Commit Guidelines