Writing in the front

Recently, WHEN I joined a new company, the leader asked me to fix the bugs in the project. When I fixed the bugs and submitted the code, I found that it was not submitted and a lot of errors were reported to me, so I found that I used ESLint to check the code when the code was committed. A closer look at package.json shows that gitHooks performed Lint-passage passage (lANToline) during pre-commit(the hook before the code commits) and husky can either commit or push While lint-staged projects only do linters of git workspace code so that you can avoid looking through the entire repository. I looked up a lot of information and read a lot of documentation in order to understand the configuration in detail, but I always felt that other articles were not very comprehensive, especially the ESLint configuration piece is difficult for beginners like me to understand, so I came up with this article about configuring front-end project workflow from scratch.

link

Refer to the article

  • How to gracefully use ESLint and Prettier in Typescript projects
  • Eslint in A Nutshell – What I learned about ESLint
  • Eslint official website in Chinese

The preparatory work

Initialize the project

Create package.json file, git init init git repository initialization, we need to do the verification of code submission, so this is installed in advance for the convenience of future development.

Configuration. The editorconfig

EditorConfig is used to maintain consistent encoding styles and Settings in the base code base, such as indent styles, TAB widths, end-of-line characters, and encodings. This is where you can develop specific Settings depending on what framework you use for your project.

Search in vscode to install the EditorConfig plug-in, create a new.edittorconfig file in the root directory, and write some configuration code.

// .editorconfig

root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120

[*.md]
trim_trailing_whitespace = false
Copy the code

Configuration Eslint

About eslint

ESLint is a QA tool that checks ECMAScript/JavaScript syntax rules and code styles to ensure that syntactically correct and consistent code is written. For those of you who aren’t familiar with ESLint, there are several sites to learn from.

Eslint in A Nutshell – What I learned about ESLint

Eslint official website in Chinese

Install ESLint in your project

yarn add -D eslint

It’s not enough to have ESLint installed in the project. What we want is to be able to prompt esLint rules in the editor as well

Install the eslint plugin in vscode

Vscode searches esLint directly and needs to be enabled in settings.json after installing the plugin.

// Settings. json partial configuration

{
    "editor.formatOnSave": false.// Automatically format each save
    "editor.defaultFormatter": "esbenp.prettier-vscode"."window.zoomLevel": 0.// The original scale
    "editor.codeActionsOnSave": { // Fix with esLint rules when saving
    "source.fixAll.eslint": false
    },
    "eslint.enable": true.// Whether to enable VScode eslint
    "eslint.options": {    // specifies the suffix for files handled by vscode's eslint
      "extensions": [
          ".js".".vue".".ts".".tsx"]}}Copy the code

Configure esLint rules

Create the.eslintrc.js file in the root directory and configure a rule.

module.exports = {
    "env": {
        "browser": true."es6": true
    },
    "rules": {
      "semi": ["error"."never"].// Forbid semicolons}};Copy the code

It is important to note that vscode requires the eslint plugin to be installed in order to have the corresponding syntax hint.

At this point, let’s write some sample code into the repository.

// src/a.js

const a = 'hello'; // I intentionally added a semicolon here to make the code inconsistent with ESLint's rules
Copy the code

Next vscode throws out errors that don’t conform to the eslint specification. It’s worth noting that eslint not only specifies which line to use, but also has a link on the official website that tells you to open the error with a click.

Let Eslint recognize Typescript

We’ve been able to make ESLint recognize JS code, but it’s not enough to realize that many libraries have been refactored in TS, Flow, and the recently updated VUe3.0 was written in TS. But whether it’s necessary to use TS on a project depends on the actual situation. Here we let ESLint recognize Typescript code.

First install dependencies:

yarn add typescript

yarn add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin

  • @typescript-esLint /parser is an ESLint parser that uses typescript ESTree to allow ESLint to clean up typescript source code.
  • @typescript-esLint /eslint-plugin is a plugin for ESLint to recognize typescript rules and we put it into the extends array.
// eslintrc.js
module.exports = {
    "parser":  '@typescript-eslint/parser'."extends": ['plugin:@typescript-eslint/recommended']."plugins": ['@typescript-eslint']."env": {
        "browser": true."es6": true
    },
    "rules": {
      "semi": ["error"."never"].// Forbid semicolons}};Copy the code

Now that ESLint recognizes Typescript code, let’s try writing some noncanonical code.

// src/b.ts

const b = 'hello';
Copy the code

Eslint –fix

Json: esLint — ext.tsx,.ts,.js –fix./ SRC esLint — ext.tsx,.ts,.js –fix./ SRC

"scripts": {
	"lint": "eslint --ext .tsx,.ts,.js --fix ./src"
}
Copy the code

Eslint can only fix part of the specification if there is a small wrench in front of the rules in the document. If there is a small wrench in front of the rules, it can be fixed.

Prettier, a device that beautifies code style

Where we can already use ESLint to standardize code, we can use the tool Prettier to format code into a uniform style.

Configuration is Prettier

Example Create the configuration file in the root directory. Prettierrc.js

module.exports =  {
  "printWidth": 120."semi": false."singleQuote": true."trailingComma": "all"."bracketSpacing": false."jsxBracketSameLine": true."arrowParens": "avoid"."insertPragma": true."tabWidth": 4."useTabs": false  
};
Copy the code

The installationPrettierRely on

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

  • Eslint-config-prettier Turns off the rule where ESLint and Prettier conflict. We place this at the end of the extends so it has a chance to override other configurations.

  • Eslint-plugin-prettier We turned off esLint’s rule, now we turn on prettier’s rule.

// eslintrc.js

module.exports = {
  "parser":  '@typescript-eslint/parser'.// Define a parser for ESLint
  "extends": ['plugin:@typescript-eslint/recommended'.'plugin:prettier/recommended'.'prettier/@typescript-eslint'].// Define a subspecification for file inheritance
  "plugins": ['@typescript-eslint'.'prettier'].// Defines the plugins that the ESLint file depends on
    "env": {
        "browser": true."es6": true
    },
    "rules": {
      "prettier/prettier": 1.// eslint-plugin-prettier Uses prettier as the ESLint rule
      "semi": ["error"."never"] // Forbid semicolons}};Copy the code

Finally, add the prettier –write command this is the syntax for prettier CLI formatting.

// package.json

"scripts": {
	"lint": "eslint --ext .tsx,.ts,.js --fix ./src"."fix": "prettier --write ./src"
}
  
Copy the code

Using a Prettier

Run the yarn fix editor to beautify the code according to the specification in.prettierrc.js.

At present, we can use yarn fix to beauten the code style, but in fact, we often forget about yarn fix before committing. Is there any way to check the code at git commit time and fix the code that is not standard, if it cannot fix it, then block the commit? Apparently there is.

Husky + Lint-staged build code workflows

Husky is a Git Hook tool that allows us to do things before code is committed to prevent bad code from being committed. Lint-staged files are files that have been modified for workspaces, which can be useful if you only want to process files that are about to be submitted.

Install Husky Lint-staged dependencies

yarn add -D husky lint-staged

Note that Windows users need to install the NPM package manager otherwise git hooks will failCopy the code

Configure Husky & Lint-staged

We need to format our code before committing it and not commit it if it doesn’t conform. Simply run Lint-staged hooks from Husky’s pre-commit hooks. Lintpassively passively does three things:

The first is to call ESLint –fix to fix code that doesn’t comply with the ESLint specification.

2 prettier –write Prettier code.

Finally, if both pass, the code is allowed to commit.

// package.json complete code

{
  "name": "lint4"."version": "1.0.0"."main": "index.js"."license": "MIT"."devDependencies": {
    "@typescript-eslint/eslint-plugin": "^ 2.29.0"."@typescript-eslint/parser": "^ 2.29.0"."eslint": "^ 6.8.0"."eslint-config-prettier": "^ 6.11.0"."eslint-plugin-prettier": "^ 3.1.3"."husky": "^ 4.2.5." "."lint-staged": "^ 10.1.7"."prettier": "^ at 2.0.5." "
  },
  "dependencies": {
    "typescript": "^ 3.8.3"
  },
  "scripts": {
    "lint": "eslint --ext .tsx,.ts,.js --fix ./src"."fix": "prettier --write ./src"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"}},"lint-staged": {
    "*{.ts,.js}": ["eslint --ext .tsx,.ts --fix ./src"."prettier --write"."git add"]}}Copy the code

case

Write some pseudo-code…..

git add .
git commit -m 'test'
Copy the code

Perfect!

conclusion

This is the end of this share, for a medium to large project specification code quality is particularly important.

Having learned how to configure a project workflow from zero, a real scenario would be to configure Husky, Lint-staged, Typescripe, etc. in Vue or React and other frameworks

A quick review of workflow highlights:

  • Use Eslint to constrain Javascript/Typescript
  • 8, Prettier Prettier code
  • Husky + Lint-staged inspections are used before commit to prevent non-standard or buggy code from entering the warehouse

Finally, thank you for reading this article and leave me a comment if you have any questions or feedback.