The background,

This article shows you how to unify your team’s code style, check code quality, and fix some low-level bugs before submitting your code. Ultimately, expect developers on the project to submit code that conforms to code specifications and styles.

Two, combination skills

Git Hook + Lint-staged + Prettier + ESLint The final implementation will be introduced first, and the role and configuration of each module will be introduced later.

2.1 Implementation Procedure

  • Have code ready for submission
  • Git add. adds to staging
  • Perform the git commit
  • Husky registers lint-staged hooks in Git pre-commit
  • Lint-passage Takes all submitted files and executes written tasks successively (Prettier + ESLint)
  • If there is an error (that doesn’t pass ESLint), stop the task and wait for the next commit, printing an error message
  • Successful submission

2.2 the installation package

npm i --save-dev husky lint-staged prettier

npm i --save-dev eslint babel-eslint eslint-plugin-react
Copy the code

2.3 Module Configuration

2.3.1 .eslintrc

{
  "env": {
    "browser": true."es6": true
  }
  "eslint": "recommended"."parserOptions": {
    "ecmaFeatures": {
      "jsx": true."impliedStrict": true}},"plugin: react"."rules": {
    "quotes": [
      "error"."single"]}}Copy the code

2.3.2 .prettier.js

module.exports = {
  // A line of up to 100 characters
  printWidth: 100.// Use 4 Spaces for indentation
  tabWidth: 4.// Instead of indentation, use Spaces
  useTabs: false.// A semicolon is required at the end of the line
  semi: false.// Use single quotes
  singleQuote: true.// The key of the object is quoted only when necessary
  quoteProps: 'as-needed'.JSX uses double quotes instead of single quotes
  jsxSingleQuote: false.// Do not need a comma at the end
  trailingComma: 'none'.// Spaces are required at the beginning and end of braces
  bracketSpacing: true.// JSX tag Angle brackets require line breaks
  jsxBracketSameLine: false.// Arrow functions with only one argument also need parentheses
  arrowParens: 'always'.// The range in which each file is formatted is the entire content of the file
  rangeStart: 0.rangeEnd: Infinity.// There is no need to write @prettier at the beginning of the file
  requirePragma: false.// There is no need to automatically insert @prettier at the beginning of a file
  insertPragma: false.// Use the default line folding standard
  proseWrap: 'preserve'.// Use lf for line breaks
  endOfLine: 'lf'
}
Copy the code

2.3.3 package.json

{..."husky": {
    "hooks": {
      "pre-commit": "lint-staged"}},"lint-staged": {
    "src/**/*.{js,jsx}": [
      "prettier --write"."eslint --fix"."git add ."]},... }Copy the code

2.3.4 Running Results

The above configuration is only an example of a combination of check methods, which can be freely combined into multiple check methods. It is not listed here. The following is an introduction to each module, if you are interested, you can continue reading.

2. Introduction and Configuration of Prettier

2.1 What is Prettier?

  • Prettier is a powerful code formatting tool that completely aligns your code style with that of your colleagues (really important…)
  • Both ESLint rules and its own configured rules are used to format code automatically
  • Prettier doesn’t check code specifications when Prettier only does code uniformity, it doesn’t check code specifications that ESLint does

2.2 The need for Prettier

  • A simple configuration automatically formats and harmonizes code styles
  • Reduce code CR time and no longer care about formatting
  • Avoid visual inspection of code format and reduce code submission times
  • Relieves ocD anxiety

2.3 How to Configure it?

2.3.1 Installing plug-ins in the Editor

  • The current development usesvscodeEditor, look in the extensionPrettier - Code formatterThe plug-in is ready to use after installation.Plug-ins for different editors
  • After installation, open the file you want to format and do the following to format the entire file or selected code snippets
1. CMD + Shift + P -> Format Document
OR
1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Code
Copy the code

[image upload failed…(image-4ACd90-1575447043750)]

2.3.2 Using a Configuration file

  1. Create a rule file: Create an. Prettierrc file in the root directory (json configuration format supported) or a.prettierrc.js configuration file

  2. Add the corresponding code to the scripts of the package.json file

{..."scripts": {
    "format": "prettier --write 'src/**/*.{js,jsx,css,less}'". },... }Copy the code
  1. Execute from the consolenpm run formatAutomatically format all files within the configuration range

Introduction and configuration of ESLint

3.1 What is ESLint?

ESLint is a code checking tool that can be flexibly configured by developers to meet specified code specifications, detect incoming code in real time during coding, and warn or report errors if code does not conform to the code specification.

3.2 Necessity of ESLint

  • Identify problems in the coding phase
  • Ensure that the code follows best practices
  • Uniform code writing specification

3.3 How to Use it

3.3.1 Configuration method

  • Configuration comments: Use JavaScript comments to embed configuration information directly into a file
  • Configuration files: Use JavaScript, JSON, or YAML files to specify configuration information

3.3.2 Configuration File Description

  1. The file format
  • JavaScriptUse:.eslintrc.jsAnd export the object that contains your configuration.
  • YAMLUse:.eslintrc.yamlor.eslintrc.ymlDefine the configuration structure.
  • JSON: used to.eslintrc.jsonDefine the configuration structure.
  • use.eslintrc, can be JSON or YAML.
  • package.json : eslintConfigIn yourpackage.jsonCreate a property in the file and define your configuration there.
  1. Environment:

Scripts design the environment in which they run. Each environment comes with a predefined set of global variables.

"env": {
  "browser": true."node": true
}
Copy the code
  1. Global variables:

Other global variables that the script accesses during execution.

"globals": {
  "React": true."MtaH5": true."TencentGDT": true
}
Copy the code
  1. Parser options:

ESLint allows you to specify JavaScript language options that you want to support. By default, ESLint requires ECMAScript 5 syntax. You can override this setting to enable support for other ECMAScript versions as well as JSX using parser options.

"parserOptions": {
  "ecmaVersion": 6."sourceType": "module".// Set it to 'script' (default) or 'module'. Your code is in the ECMAScript module.
  "ecmaFeatures": { // An object indicating which other language features you want to use
    "jsx": true./ / enable JSX
    "impliedStrict": true // Enable global strict mode}},Copy the code
  1. The plug-in

To configure plug-ins in the configuration file, use the plugins key that contains the list of plug-in names. The eslint-plugin- prefix can be omitted from the plug-in name.

"plugins": [
  "react"."eslint-plugin-react"
]
Copy the code
  1. extension

An extension is a direct use of rules that someone else has already written. Rules configured in the rules property are based on that rule

"extends": [
  "standard"
  "eslint:recommended"."plugin:react/recommended"].Copy the code

Recommended extension configuration:

Standardjs, Airbnb, ESlint-config-alloy

  1. Rules:

ESLint comes with a lot of rules. You can use comments or configuration files to modify the rules to be used in your project. To change a rule setting, you must set the rule ID to one of the following values

  • "off"0: Disable rule
  • "warn"1: Enable the rule to use warning level errors (does not cause the program to exit)
  • "error"2: enable rules that use error-level errors (when triggered, the program exits)
"rules": {
  "strict": 2,}Copy the code

3.3.3 How do I Detect

Add the run command to the scripts of package.json to set the files in the SRC directory to be checked

{..."scripts": {
    "lint": "eslint ./src"
    "lintFix": "eslint ./src --fix"},... }Copy the code

Run the following command on the console:

// Code check
npm run lint
// Code check and fix
npm run lintFix
Copy the code

4. Introduction and configuration of Git Hook

4.1 Git hooks

Like other version control systems, Git can trigger custom scripts when certain important actions occur. This is the submission workflow hook

4.1.1 pre-commit

  • The hook runs before the commit information is typed
  • Used to check the snapshot to be committed
  • If the hook exits with a non-zero value, Git abandons the commit
  • You can usegit commit --no-verifyTo get around that
  • You can use this hook to check if your code style is consistent

4.1.2 prepare-commit-msg

  • The hook runs after the default information is created before starting the commit information editor
  • Allows you to edit the default information that submitters see

4.1.3 How do I Configure it

To add the configuration to package.json, run the following command to add it to scripts:

{
  "scripts": {
    "lint": "eslint ./ --cache --ignore-pattern .gitignore"."precommit-msg": "echo 'Pre-commit checks... ' && exit 0"
  },
  "pre-commit": [ "precommit-msg"."lint"]."devDependencies": {
    "eslint": "^ 2.12.0"."pre-commit": "^ 1.1.3." "}}Copy the code

4.2 Husky

Configure husky in our package.json and execute the corresponding git hook phase. Therefore, there is no need to configure git hook script files.

{
  "husky": {
    "hooks": {
      "pre-commit": "npm test"."pre-push": "npm test"}}}Copy the code

Five,lint-staged

Lint-staged submission only tests the files that have been modified before each submission. Passage Ten is a concept from Git commit -a, or Git Add and Git commit. Any changes you make will go through the wait area.

// package.json{..."scripts": {
    "precommit": "lint-staged".// git commit Execute this command, which is tuning lint-staged
  },
  "lint-staged": {   / / lint - staged configuration
    "src/**/*.{js,jsx}": [
      "prettier --write"."eslint --fix"."git add"]},... }Copy the code

Six, summarized

Some of the ways and means of project practice are summarized above. The use of methods can improve project quality. Standardized code can reduce the occurrence of problems to a certain extent. Code readability has also improved.