On the road to code specification, our ultimate goals are:

All the developers on the team use one set of code to standardize the rules, and we don’t have to spend much effort on formatting for formatting’s sake. We want an automated tool that can help us check if our code is standard, and if it is not, it can automatically help us format it according to the given specification.

Eslint and Prettier in general, prettier is used to format code. Eslint implements the setting of code specification rules and warnings such as WARN and error on code. So our big goal should be esLint, and then integrate Prettier.

VSCode editor extension plug-in

  1. Prettier – Code formatter – Visual Studio Marketplace

Prettier-code Formatter GitHub Prettier /prettier-vscode: Visual Studio Code Extension for Prettier

  1. Vetur – Visual Studio Marketplace
  2. ESLint – Visual Studio Marketplace
  3. EditorConfig for VS Code – Visual Studio Marketplace

Project depend on

EditorConfig

Official document: EditorConfig

Summary: Write code across editors and ides, maintaining a consistent simple coding style;

Prettier

Official document: Prettier

Introduction: focus on code formatting tools, beautify code;

The installation

prettier

NPM install -- save-dev -- save-exact prettier

eslint-config-prettier

NPM install - save - dev eslint - config - prettier

Make sure that the ESLint configuration does not conflict with the Prettier configuration. Rules that aren’t necessary and conflict with Prettier when ESLint is installed automatically disabled

lint-staged

npx mrm lint-staged

Use Prettier in conjunction with the pre-commit tool. This allows you to reformat files marked “staged” by git Add before committing. Before installing, make sure Prettier is installed and in the devDependencies section.

IO /docs/en/pre…

Ignore the Prettier

Use the. Prettierignore file to completely ignore (that is, not reformat) certain files and folders.

# Ignore artifacts:
build
coverage

# Ignore all HTML files:
*.html
Copy the code

Prettier summary

  • Install the correct version of the Prettier plug-in in your editor to make sure everyone on the team is installing the same version
  • The dependency on installing the correct version of Prettier locally in a project to make sure everyone on the team is installing the same version
  • Add a.prettierrc.jsonConfiguration file to tell the editor that you are usingPrettier;
  • Add a.prettierignoreConfiguration files tell your editor which files do not need formatting;
  • By running theNPX prettier - write.To format files for the entire project;
  • By running theNPX prettier - check.Check the format specification of each project file;
  • Use eslint-config-prettier to make sure esLint and Prettier work together
  • Setting the pre-commit hook ensures that the code is formatted every time it commits.

ESLint

Official documentation: ESLint – Pluginized JavaScript code detection tool – ESLint Chinese documentation

Introduction: code quality inspection, code style constraints, etc

A prerequisite for

  • Node. Js (> = 6.14);
  • NPM version 3 +.

The installation

ESLint

NPM install eslint - save - dev

babel-eslint

npm install babel-eslint --save-dev

eslint-config-prettier

npm install eslint-config-prettier --save-dev

Initialize the ESLint configuration file

Start creating an ESLint configuration file using esLint –init

Error level

  • “Off” or 0 – Disables the rule
  • “Warn” or 1 – Treat the rule as a warning (does not affect exit codes)
  • “Error” or 2 – Treats the rule as an error (exit code 1)

Official recommendation Rules

  • use"extends": "eslint:recommended"To enable the recommendation rules, seeList of available rules – ESLint

Configuration instructions

  • Environments – Specifies the environment in which the script runs. Each environment has a specific set of predefined global variables.
  • Globals – Additional global variables that the script accesses during execution.
  • Rules – Enabled Rules and their respective error levels.
  • Plugins – third-party plugins
  • Extends from
  • Parser – a Parser, ESLint uses Espree as its default Parser.
  • ParserOptions – Often used to set some configuration of the grammar parser.

Ignore ESLint

New.eslintignore file

You can tell ESLint to ignore specific files and directories by creating an.eslintignore file in the project root

The.eslintignore file is a plain text file in which each line is a glob pattern indicating which paths should be ignored for detection. For example, the following will ignore all JavaScript files: ‘

**/*.js
Copy the code

Remove common comments from ESLint files

/* eslint-disable */ -- disable all rules at the top of the file without checking the entire file scope /* eslint-disable no-alert, No-console */ -- disables some rules // eslint-disable-line -- disables rules on the current line // eslint-disable-next-line -- disables rules on the next lineCopy the code
Common command lines

View all command-line options: eslint -h

Auto-fix problems: eslint — fix

Disable configuration in eslintrc: eslint – — no-eslintrc

To a single file or a directory files formats: eslint [options] [file | dir | glob] *

Use other rules in the specified directory: eslant — -rulesdir [path::String]

Reports only errors, default false: eslint — -quiet

Only files that have been altered are checked. Default false: eslint – – cache

Explicitly format the report output file: eslint -o, – output-file path::String

Summary of usage

  1. Install VSCode plug-in separately:Prettier,ESLint,EditorConfig;
  2. Local installation dependencyeslint,eslint-config-prettier,babel-eslint,prettier,eslint-config-prettier,eslint-config-prettierRely on;
    npm install eslint eslint-config-prettier babel-eslint prettier eslint-config-prettier eslint-config-prettier --save-dev
    Copy the code
  3. Install the Pre – commit hooks:npx mrm lint-staged
  4. performgit commitESLint will format check and fix automatically, warning syntax that cannot be fixed automatically and preventing commit;
  5. Add the command to package.json usingnpm run lintCheck the syntax and formatting usednpm run lint --fixFixes to syntax and formatting
"scripts": {
    "lint": "eslint --ext .js,.vue src"."lint-fix": "eslint --fix --ext .js,.vue src/"
  },
Copy the code

The recommended configuration

EditorConfig Configuration:.editorConfig file

# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
# Scope: Write code across editors and IDES, keeping a consistent simple coding style

# special property that should be specified at the top of the file outside of any sections. Set to true to stop .editorconfig files search on current file.
root = true 

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf # set to lf, cr, or crlf to control how line breaks are represented.
insert_final_newline = true # set to true to ensure file ends with a newline when saving and false to ensure it doesn't.

# Indentation override for all JS under lib directory
[**.{js,vue,ts}]
charset = utf-8 # set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.
indent_style = space # set to tab or space to use hard tabs or soft tabs respectively.
indent_size = 4 # use 4 spaces instead of tabs;
trim_trailing_whitespace = true # remove trailing white space characters when saving

[*.md]
trim_trailing_whitespace = false

# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 4
Copy the code

Prettier Configuration: the. Prettierrc file

{
    "singleQuote": true."semi": true."arrowParens": "avoid"."bracketSpacing": false."embeddedLanguageFormatting": "auto"."htmlWhitespaceSensitivity": "css"."insertPragma": false."jsxBracketSameLine": false."jsxSingleQuote": false."printWidth": 200."proseWrap": "never"."quoteProps": "as-needed"."requirePragma": false."tabWidth": 4."trailingComma": "none"."useTabs": false."vueIndentScriptAndStyle": false
}
Copy the code

ESLint configures the.eslintrc.js file

module.exports = {
    env: {
        es6: true.browser: true.node: true.commonjs: true.amd: true
    },
    extends: ['eslint:recommended'.'plugin:vue/essential'.'plugin:prettier/recommended'].parserOptions: {
        ecmaVersion: 12.sourceType: 'module'.parser: 'babel-eslint'
    },
    plugins: ['vue'.'prettier'].rules: {
        'prettier/prettier': 'error'.indent: ['error'.4].'linebreak-style': ['error'.'unix'].quotes: ['error'.'single'].semi: ['error'.'always']}};Copy the code