preface

Hello, I’m a mouse!

Code specification is a cliche. As a serious code cleanliness freak, I can accept multiple styles of code, but mixing messy styles with scattered indentation is unacceptable.

Oh my god! This lack of indentation, or a mix of different code styles, is really annoying.

This is why code specifications are so important. The larger the project, the more people involved, the more valuable this constraint becomes, reducing the cost of communication within the team.

The code formatting tool is the implementation of code specification, generally speaking, there are two stages of formatting project development stage, project submission stage.

summary

Passage Ten This article introduces how to install and configure ESLint, Prettier, Husky, Lint-staged code to conform to code specifications (automatic formatting, save formatting, etc.) A quick introduction to EditorConfig by the way.

  • The first part is the project development stage
    • eslint
    • prettier
    • Compatible with esLint and Prettier
    • Configure the VScode environment file
    • Unified environment configuration using EditorConfig
  • Part II Project submission stage
    • husky
    • lint-staged
    • Install Huksy + Lint-Staged
    • commitlint

The first part is the project development stage

Eslint and Prettier this section introduces esLint and Prettier and provides basic configuration, as well as editor configuration.

Eslint

The purpose of LINT is to flag suspicious, incorrect parts of JS/TS code.

Eslint is essentially a simple bug checker that shows potential errors in code before compilation.

Find and fix problems in your JavaScript codeCopy the code

It checks the code strictly according to the rules we configured, and there are two types of common errors:

  1. Code quality error
  2. Code style error

We use constraint rules to unify styles and avoid common errors in javascript code to reduce the difficulty of review.

Configuration Eslint

  1. Install eslint
npm install --save-dev eslint
yarn add eslint --dev
Copy the code

Ps: If you are building a project using scaffolding, it will generally come with ESLint.

  1. Creating a Configuration File

Switch to the project root directory and create the.eslintrc.js configuration file and.eslintignore ignore file

  1. Initialize the configuration file
npx eslint --init
Copy the code

Select and build the configuration as prompted:

The following is my personal document for your reference:

module.exports = {
  env: {
    browser: true.es2021: true.node: true,},extends: [
    'plugin:react/recommended'.'airbnb',].parser: '@typescript-eslint/parser'.parserOptions: {
    ecmaFeatures: {
      jsx: true,},ecmaVersion: 12,},plugins: [
    'react'.'@typescript-eslint',].rules: {}};Copy the code

You can add changes to.eslintrc.js to suit your own project needs, and I’ve added support for typescript.

Extend the typescript

  1. Installing the parser

Eslint does not parse typescript by default, additional parsers need to be installed.

npm i --save-dev typescript @typescript-eslint/parser
Copy the code
  1. Setting up the parser
{
  "parser": "@typescript-eslint/parser"
}
Copy the code
  1. Add the plug-in

Prettier

Eslint can provide some style constraints, but the industry is specialized, and Eslint’s specialty is Javascript error correction.

Prettier, an independent code formatting tool for unifying the style of code in many languages

An Opinionated Code FormatterCopy the code

Opinionated

Why Prettier is Opinionated?

Prettier is a code formatter for default configuration, providing only a few configurable items in order to make it easier to learn and choose between configuration items

The idea is to convert our code into an AST syntax abstraction tree, and finally into code in the corresponding style, removing all the original styles in the process.

Supports multiple file types

configuration

  1. The installation
npm install --save-dev prettier --save-exact
Copy the code

–save-exact Indicates the exact version of the package. ^ and ~ do not exist

  1. Creating a Configuration File
  • .prettierrc.json Configuration file
  • .prettierIgnore Ignores a file

Compatible with Eslint and Prettier

Eslint also has some code normalized configurations that conflict with Prettier, so compatibility configuration is needed.

There are generally two ways to modify ESLint to prettier and vice versa.

Compatible with eslint-config-prettier

  1. Installing dependent plug-ins
npm install eslint-config-prettier
Copy the code
  1. Modify the ESLint configuration

Add prettier to the end of the extends array in the ESLint configuration file to override part of the rule.

{
    "extends": [
        "prettier"]}Copy the code

Modified Pretter for ESLint

Modify the.prettierrc.json file:

{
  "prettier": {
    "eslintIntegration": true."singleQuote": false."semi": true."insertPragma": false."trailingComma": "none"."arrowParens": "avoid"."endOfLine": "lf"}}Copy the code

Configure the VScode environment file

The purpose of configuring vscode is twofold, one to automatically format the implementation code (triggered when saving) and the other to unify the plugins used by files (lint, Formatter, etc.).

  1. Install the vscode plug-in
  • Eslint plug-in

  1. Configuring environment Files

There are two types of environment configuration files in vscode:

  • User area: Global configuration
  • Workspace: Project configuration

In general, project local configuration is performed for the project workspace.

  • Search for Setting using CTRL, or File => Preferences => Settings

  • Clicking on what appears to edit in settingsj.json will generate.vscode/settings.json in the project root directory

    Or we can create it manually

  • Then change the configuration file:

    The following is my configuration for reference:

    {
        // Editor TAB size is 2 Spaces
        "editor.tabSize": 2.// newline after 100 columns
        "editor.wordWrapColumn": 100.// Automatically fixes errors when saving
        "editor.codeActionsOnSave": {
            "source.fixAll": true,},// Automatic formatting when saving
        "editor.formatOnSave": true."eslint.options": {
        // specifies the suffix for files handled by vscode's eslint
        "extensions": [".js".".ts".".tsx"]},// eslint checks file types
        "eslint.validate": [
         "javascript"."typescript"."javascriptreact"."typescriptreact"].// Enable vscode file path navigation
        "breadcrumbs.enabled": true.// Displays special characters generated when markDown is switched between Chinese and English
        "editor.renderControlCharacters": true.// Set the end of line sequence to LF (\n)/CRLF (\r\n)
        "files.eol": "\n".// Enable default formatting rules for each language
        "[html]": {
          "editor.defaultFormatter": "esbenp.prettier-vscode"
        },
        "[css]": {
          "editor.defaultFormatter": "esbenp.prettier-vscode"
        },
        "[less]": {
          "editor.defaultFormatter": "esbenp.prettier-vscode"
        },
        "[javascript]": {
          "editor.defaultFormatter": "esbenp.prettier-vscode"}},Copy the code

    Note: the new version of vscode uses editor.codeacrionsonsave for automatic fixes.

Unified environment configuration using EditorConfig

The above configuration of vscode for verification is a long and annoying discussion. Most importantly, it is limited to vscode environments.

Is there a configuration that works with all editors and ides? It is editorConfig.

We do this by configuring EditorConfig.

  1. Creating a Configuration File

Editorconfig is created in the root directory as usual

  1. The configuration file

For more information, see EditorConfig.org:

# EditorConfig is awesome: https://EditorConfig.org# flag whether the top EditorConfig configuration is root =trueSet the default line end [*] end_of_line = LF insert_final_newline =true{py}] charset = UTf -8Py] indent_style = space indent_size =4

[Makefile]
indent_style = tab

[lib/**.js] indent_style = space indent_size = 2 # Indent_style = space indent_size = 2Copy the code

Part II Project submission stage

The project commit phase refers to the Git commit phase. By adding a pre-commit hook, we automatically perform checks and standardize the code every time we commit.

The checks we routinely add include code style checks and commit Messages.

Husky

Early Git hooks had to be placed in.git/hooks files, which were not portable and shared among teams.

Husky is a tool that adds hooks to Git projects. A hook can be interpreted as a callback function for a specific time node.

We achieved the constraints by using HusKY to check the code during the pre-commit phase of the project.

It automatically loads the corresponding script into.git/hooks.

configuration

We can do this by setting the husky property in package.json:

 "scripts": {
    "lint": "eslint src"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run lint"}},Copy the code

This will trigger the Lint script before each commit.

Lint-staged

Lint-staged projects can be very time-consuming if we check the entire project file before each submission, and this is exactly what lint-staged projects are designed to do.

Lint-staged files can be filtered out from staged files (that is, the files that were submitted this time) and commands can be executed against those files.

Install HusKY + Lint-staged

npm install -g mrm mrm-task-lint-staged
mrm lint-staged
Copy the code

Of course, you can also use NPX if you don’t want to install MRM

npx mrm lint-staged
Copy the code

It will install Husky and Lint-staged and perform basic configuration configurations on your project:

//package.json
{
   / /...
  "devDependencies": {
    "eslint-config-prettier": "^ 8.2.0"."husky": "^ 6.0.0"."lint-staged": "^ 10.5.4"."prettier": "^ 2.2.1." "
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"}},"lint-staged": {
    "*.{js,css,md,ts,tsx}": "prettier --write"
  }
Copy the code

commitlint

A good project also needs to keep a clear Git history, so we need to standardize the code, as well as the commit information.

For example, we advocate fix list can’t open rather than fix a bug.

Commitlint is intended to bind each project participant.

configuration

  1. The installation

    npm install -D @commitlint/config-conventional @commitlint/cli
    echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
    Copy the code
  2. configuration

    Create the configuration file commitlint.config.js in the root directory

  3. Introduce pre-commit hooks

    //package.json
    {
       / /...
      "husky": {
        "hooks": {
          "pre-commit": "lint-staged"."commit-msg": "commitlint -E HUSKY_GIT_PARAMS"}},"lint-staged": {
        "*.{js,css,md,ts,tsx}": "prettier --write"
      }
    Copy the code

conclusion

This is the project specification practice I collected with 2021/4/20. It may not be an optimal solution, but it is a common collocation.

If these tools are helpful to you, please ask for a thumbs up 👍 hh

Of course, you are also welcome to put forward your views and discuss together.

This article refer to

  • Eslint can be configured with rules eslint.org/docs/rules/
  • Combining with the typescript prettier beautification project www.robertcooper.me/using-eslin…
  • Vscode eslint plug-in marketplace.visualstudio.com/items?itemN…
  • Vscode code formatting blog.csdn.net/userkang/ar…
  • The zhuanlan.zhihu.com/p/81764012 Prettier and see this one
  • Use a husky avoid bad git commit zhuanlan.zhihu.com/p/35913229