ESLint + StyleLint + Prettier + VSCode to create the most elegant front-end development experience

ESLint + StyleLint + Prettier + VSCode to create the most elegant front-end development experience


introduction

For a mature front-end team, unified coding standards and submission standards are especially important. To ensure order, uniform style, and order, it is not of much practical value to just write the specification in the document . No one wants to read the rules one by one, memorize them, and finally follow the rules when writing code.

How to develop gracefully and keep the moat of code quality is a question worthy of our consideration.

This article is a side story of the above article. In addition to the content of the original article, StyleLint is added to check the style, Preiiter is added to beautify the code and cooperate elegantly with ESLint and StyleLint, and VSCode configuration is added to realize the whole set of development experience under VSCode Works out of the box .

moat

overview

An ideal development experience can be abstracted like this:

Only care about the business code, with an elegant workflow , all the code is in the source code when debugging, and the product meets the specification requirements.

However, in order to truly meet the requirements of the specification, it is far from enough to rely solely on literal constraints and development awareness. Engineering methods must be used to allow the development to use automated tools to complete the requirements of the specification during the development process, and the development itself can devote itself to invested in business development .

**This article combines eslint, stylelint, prettier, vscode, standardjs, husky, lint-staged, commitizen, commitlint and other tools to systematically build a front-end specification solution.
**

Subsequent consideration is to write the entire set of specifications as a tool (moat), which can be applied to other project projects with one click.

coding constraints

The front-end coding specification mainly includes two parts: JS and CSS. ESLint and Stylelint are used respectively in landing projects, and Prettier is combined to make the coding style uniform. As shown below:

ESLint + StyleLint + Prettier to complete the automation of coding constraints

ESLint

The project integrates ESLint to automatically find and fix problems in JavaScript. Where .eslintrc.js is the configuration file of eslint. According to different projects, the configuration will be different. The configuration content used in this project is as follows:

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['plugin:react/recommended', 'standard', 'plugin:prettier/recommended'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react', '@typescript-eslint'],
  rules: {
    // eslint 规则写这里
    'comma-dangle': ['error', 'only-multiline'],
  }
}

For the specific meaning and function of configuration, please refer to [ESLint]( https://github.com/eslint/eslint ) official website documentation.

The packages that need to be installed are:

eslint : ESLint program entry, set in lint-staged to execute the program for JS files
eslint-config-standard : a set of general ESLint rule configuration.
eslint-config-prettier : Turn off ESLint rules that may conflict with Prettier, and resolve conflicts with ESLint + Prettier
eslint-plugin-prettier : A plugin for Prettier that makes it possible to use ESLint + Prettier in combination. Let Prettier's formatting operation be performed in the process of ESLint, and the formatting problems found by Prettier will be automatically repaired in the process of ESLint

Among them, eslint-config-standard is a set of common ESLint rule configurations in the industry, provided by JavaScript Standard Style. For specific individual rules, please refer to: https://standardjs.com/rules.html

JavaScript Standard Style

The standard configured in the extends field in the above ESLint configuration file indicates that the rules for verification and repair use the JavaScript Standard Style standard

standardjs can detect style and program problems in advance, reduce the repeated modification process in the code review process, save a lot of time and maintain global unity.

By default, it is enough to use standardjs, no need to formulate additional rules, if necessary in actual development, it can be configured in the rules of .eslintrc.js

StyleLint

Stylelint is a powerful, advanced CSS code checker (linter) that helps developers avoid errors in CSS code and maintain a consistent coding style.

It has the following functions:

Understands the latest (modern) CSS syntax and features
Has over 170 built-in rules to catch errors and enforce coding conventions
Supports plugins to create your own rules
Automatically fixes most code formatting issues
Has a growing community and is Used by Google, GitHub, and WordPress

can also be extended to:

Parses CSS-like syntax such as SCSS, Sass, Less, and SugarSS
to extract embedded style code from HTML, Markdown, and CSS-in-JS objects and template text

The packages that need to be installed are:
stylelint : the program entry of Stylelint, set in lint-staged to execute the program for style files
stylelint-config-standard : the rule configuration set agreed by Stylelint, Stylelint executes
stylelint-config-prettier according to this rule : Close the rules that may conflict with Prettier, and solve the conflict problem when Stylelint + Prettier
stylelint-prettier : Prettier's plug-in, making it possible to use Stylelint + Prettier. Let Prettier's formatting operation belong to the Stylelint process, and the formatting problems found by Prettier will also be automatically repaired during the Stylelint process

Among them, stylelint-config-standard is a set of industry-wide Stylelint rule configurations. Include specific rules like: The Idiomatic CSS Principles , Google's CSS Style Guide , Airbnb's Styleguide , and @mdo's Code Guide .

Prettier

Prettier is an "attitude" code formatting tool that supports a large number of programming languages. Compared with ESLint (which mainly focuses on grammatical errors and does some formatting), it focuses more on code style and style. Therefore, it is necessary to use Prettier and ESLint together in daily development to be elegant and impeccable.

For configuration of this project, refer to the prettier.config.js file

The packages that need to be installed are:

prettier

commit constraints

The configuration of ESLint + Stylelint + Prettier is completed above, and yarn eslint xx.tsx, yarn stylelint xx.less, yarn prettier xx.md , etc. can be used in the project to verify and repair different files. However, it is not realistic to rely on development to execute commands manually, and engineering methods are still needed to help development complete automatically .

The following describes the use of husky + lint-staged + commitizen + commitlint to automatically perform verification and repair when submitting, and at the same time constrain the format of the submission itself. The core process is shown in the figure below:

Submit constraint core process diagram

commitizen

Commitizen is a tool for formatting git commit messages, which provides a query-style way to get the required commit information.

Inquiry Submission

cz-conventional-changelog is used to specify what information needs to be entered when submitting, such as whether the type of submission is to repair problems or function development, the scope of submission impact, etc. cz-conventional-changelog is a rule provided by the official website. You can develop suitable rules yourself according to the actual situation of the project, but they are sufficient at this stage, and there is no need to modify them.

Since the windows platform does not support multiplexing git commit to submit, it can be submitted through the cz script command in package.json

 // package.json
 "scripts": {
    
    
    "cz": "git-cz"
 } 

In essence, execute the git-cz command in the root directory of the project to submit, so you can use any one of yarn cz**, yarn git-cz , npm run cz , **npx git-cz to complete your submission.

The packages that need to be installed are:
commitizen
cz-conventional-changelog

husky + lint-staged

husky is a tool for processing git hooks, which can intercept git hooks and make it possible to " verify submission format ", " verify code " and so on.

lint-staged is a tool for lint operations on the staging area. First, it saves time by not needing to lint the global code each time; second, when applying lint rules to old projects, all submissions cannot pass due to historical reasons, so it is also necessary to only lint the code that is about to be submitted.

For tool usage instructions, see: husky

Use the lint-staged tool in combination to detect only the currently modified part.

// package.json
 "lint-staged": {
    
    
  "*.{js,jsx,ts,tsx}": [
     "eslint --fix"
  ],
  "*.{less,css}": [
     "stylelint --fix"
  ]
 }

After installing husky, there will be an additional .husky folder in the root directory of the project for the configuration of git hooks. At the same time, add lint-staged configuration in package.json, as shown above, when submitting js, jsx, ts, tsx Automatically use eslint for verification and automatic repair, and for less and css, automatically use styleint for verification and repair when submitting.

Only the passed code will be submitted. If there is something that does not meet the specifications, an error will be reported when submitting, and it can be repaired as required.

The packages that need to be installed are:

husky : handle git hooks
lint-staged : only valid for the staging area

Using husky+lint-staged will intercept and automatically repair when submitting. If errors can be prompted in real time during development, and errors can be automatically repaired when saving, you can avoid the problem of intensively repairing errors when submitting. For how to implement, please refer to the project configuration chapter.

commitlint

The query-style submission method is implemented through commitizen above, but there is no way to guarantee that the development will abide by this agreement. In order to prevent development errors, use git commit to submit the code yourself, so use commitlint to verify the submission information before submitting it into the warehouse.

commitlint is a tool for checking that commits conform to the specification.

The required installation packages are:

@commitlint/cli : Commitlint, the execution entry for verification, is used in conjunction with husky to use the git hook of commmit-msg to check the submission information when submitting the code. If it does not meet the submission specifications, an error message will be reported.
@commitlint/config-conventional A set of common submission information verification schemes, produced by the Angular team. You can also customize your own team's specifications if needed.

Engineering configuration

The standard and verification tools were deployed earlier, and the submission was also intercepted, which can already guarantee the quality of the code. But in order to further improve the efficiency of development, we don't want to find a bunch of verification errors when submitting.

The following takes vscode as an example to realize the function of prompting errors in real time during the development process and automatically formatting & repairing with one click , so as to achieve consistent out-of-the-box use for all developments.

Other editors are similar, you can refer to the configuration of their respective editors

VSCode plugin

If you want the editor to automatically prompt errors and fix them automatically during development, be sure to install the ESLint plug-in and StyleLint plug-in

The plug-ins that the project depends on are configured in .vscode/extensions.json. If there are new dependent plug-ins in the future, they can be configured here and submitted to ensure that all developers rely on the unification of plug-ins.

{
    
    
 "recommendations": ["dbaeumer.vscode-eslint", "stylelint.vscode-stylelint"]
}

Currently only ESLint and StyleLint are needed.

After the plug-in is installed, for errors in the code, an error message as shown in the following figure will be displayed:

Quoted from Modern.js, invaded and deleted

At the same time, there are hints in the file name and the preview box on the right, which are very eye-catching.

VSCode configuration

The vscode configuration that the project depends on is in .vscode/setting.json. These configurations make it possible to " edit the editor to prompt for errors in real time ", " automatically repair when saving ", and " automatically repair when right-clicking to format the file ".

After installing the plug-in, you need to configure the plug-in accordingly to adapt to different development needs.

For example, it is necessary to set the default formatting tools of typescript, javascript, typescriptreact, javascriptreact and other files to automatic repair of eslint. In this way, in these files, right-click - format the document to automatically invoke eslint for verification and formatting.

StyleLint is configured in the same way.

The configuration of the project in this article is as follows, and the automatic lint when saving is turned on, so that when saving the file, all checks and repairs are automatically completed.

{
    
    
  "eslint.run": "onType",
    "eslint.codeActionsOnSave.mode": "all",
      "eslint.format.enable": true, // 允许eslint 格式化对应的文件
        "[typescript]": {
    
    
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
      "editor.codeActionsOnSave": {
    
    
      // 开启保存时执行eslint进行校验和格式化
      "source.fixAll.eslint": true
    },
    "editor.formatOnSave": false // 所以编辑器默认的格式化设置为false,避免重复格式化
  },
  "[javascript]": {
    
    
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
      "editor.codeActionsOnSave": {
    
    
      "source.fixAll.eslint": true
    },
    "editor.formatOnSave": false
  },
  "[typescriptreact]": {
    
    
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
      "editor.codeActionsOnSave": {
    
    
      "source.fixAll.eslint": true
    },
    "editor.formatOnSave": false
  },
  "[javascriptreact]": {
    
    
    "editor.defaultFormatter": "dbaeumer.vscode-eslint",
      "editor.codeActionsOnSave": {
    
    
      "source.fixAll.eslint": true
    },
    "editor.formatOnSave": false
  },
  "[sass]": {
    
    
    "editor.defaultFormatter": "stylelint.vscode-stylelint", // 设置编辑器默认格式化工具为stylelint
      "editor.codeActionsOnSave": {
    
    
      "source.fixAll.stylelint": true // 保存时自动使用sytlelint 修复
    },
    "editor.formatOnSave": false // 关闭编辑器默认的保存格式化
  },
  "[css]": {
    
    
    "editor.defaultFormatter": "stylelint.vscode-stylelint",
      "editor.codeActionsOnSave": {
    
    
      "source.fixAll.stylelint": true
    },
    "editor.formatOnSave": false
  },
  "[less]": {
    
    
    "editor.defaultFormatter": "stylelint.vscode-stylelint",
      "editor.codeActionsOnSave": {
    
    
      "source.fixAll.stylelint": true
    },
    "editor.formatOnSave": false
  }
}

Summarize

Finally, I hope that every front-end warehouse will successfully defend the city!

Guess you like

Origin blog.csdn.net/zqd_java/article/details/128398198