8

image.png

Lazy Raiders (Quick Start and Use Summary)

Don't have time to dig deeper? 6 steps to quickly take you to configure the team code specification, are you not happy to copy homework!

  1. Install VSCode plugins respectively: Prettier , ESLint , EditorConfig ;
  2. Pull the latest code, execute npm install , and automatically download dependencies such as eslint , eslint-config-prettier , babel-eslint , prettier , eslint-config-prettier

    npm install eslint eslint-config-prettier babel-eslint prettier eslint-config-prettier --save-dev
  3. Add .prettierrc , .stylelintrc , .editorconfig and other configuration files as needed to standardize the team code. For specific configuration, please refer to the recommended configuration at the end of this article.
  4. Install Pre-commit Hook: npx mrm lint-staged
  5. After executing git commit , ESLint will check the format and repair it automatically. For the syntax that cannot be repaired automatically, it will warn and prevent the commit;
  6. Add commands to package.json, use npm run lint check syntax and format, use npm run lint —fix to fix syntax and format

    "scripts": {
     "lint": "eslint --ext .js,.vue src",
     "lint-fix": "eslint --fix --ext .js,.vue src/"
      },

full text is over! (Manual

ESLint

What is ESLint

It is an open source JavaScript linting tool. It uses espree to parse the JavaScript code into an abstract syntax tree (AST), and then analyzes our code through the AST, thus giving us two hints:

  1. Code quality issue : There may be problems with the usage (problematic patterns)
  2. Code Style Issue : Style doesn't adhere to certain style guidelines
    Official document: ESLint - Plug-in JavaScript code detection tool - ESLint Chinese document

prerequisites

  • Node.js (>=6.14);
  • npm version 3+。

use

install ESLint

npm install eslint —save-dev

install babel-eslint

npm install babel-eslint --save-dev

install eslint-config-prettier

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

Make sure that the ESLint configuration does not Prettier configuration. ESLint unnecessary and conflicting rules Prettier will be automatically closed;

Initialize the ESLint configuration file

Use eslint --init start creating a ESLint profile

error level

  • "off" or 0 - turn off the rule
  • "warn" or 1 - treat the rule as a warning (does not affect exit codes)
  • "error" or 2 - treat the rule as an error (exit code 1)

Official Referral Rules

Configuration instructions

  • Environments - Specifies the environment in which the script will run. Each environment has a specific set of predefined global variables.
  • Globals - Additional global variables accessed by the script during execution.
  • Rules - Enabled rules and their respective error levels.
  • plugins - 3rd party plugins
  • Extends - Inheritance
  • Parser - Parser, ESLint uses Espree as its parser by default.
  • parserOptions — Commonly used to set some configuration of the parser.

Ignore ESLint

Added .eslintignore file, you can tell ESLint to ignore specific files and directories by creating a .eslintignore file in the project root directory
The .eslintignore file is a plain text file where each line is a glob pattern indicating which paths should be ignored for detection. For example, the following will ignore all JavaScript files:

**/*.js

cancel ESLint common comment

/* eslint-disable */ —- 禁用全部规则 放在文件顶部则整个文件范围都不检查 
/* eslint-disable no-alert, no-console */ -— 禁用某些规则 
// eslint-disable-line -— 当前行上禁用规则 
// eslint-disable-next-line —- 下一行上禁用规则

Common command lines

See all command line options: eslint -h

eslint —-fix issues: 061ee63992e11e

Disable using config in eslint -—no-eslintrc

Format a single file or directory of files: eslint [options] [file|dir|glob]*

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

Only report errors, default false: eslint —-quiet

Only check files with changes, default false: eslint -—cache

Explicitly formatted report's output file: eslint -o, —output-file path::String

Prettier

What is Prettier

Official document: Prettier
We mentioned above that ESLint mainly solves two types of problems, but in fact, ESLint mainly solves the code quality problem . Another type of code style problem is actually not completely finished with ESLint, because these problems are "not so important", code quality problems mean that the program has potential bugs, and style problems are just unpleasant to look at at best.
At this time, Prettier appeared. Prettier claimed to be an opinionated code formatter (opinionated code formatter). Prettier believed that the format was very important. , so it is equivalent to Prettier took over the code format of the two problems. , and using Prettier + ESLint completely solves both problems .

image.png

use

install prettier

npm install —save-dev —save-exact prettier

install eslint-config-prettier

npm install —save-dev eslint-config-prettier

Make sure that the ESLint configuration does not Prettier configuration. ESLint unnecessary and conflicting rules Prettier will be automatically closed;

install lint-staged

npx mrm lint-staged

Use Prettier with the pre-commit tool. This can reformat files marked "staged" via git add before committing. Before installing, make sure Prettier is installed and in devDependencies .

For other solutions, see https://prettier.io/docs/en/precommit.html

Ignore Prettier

Use the .prettierignore file to completely ignore (ie not reformat) certain files and folders.

# Ignore artifacts:
build
coverage

# Ignore all HTML files:
*.html

Summarize

  • Install the correct version of the Prettier plugin in your editor, making sure everyone on the team has the same version installed;
  • Install the correct version of Prettier dependencies locally in the project to ensure that everyone on the team installs the same version;
  • Add a .prettierrc.json configuration file to tell the editor that you are using Prettier ;
  • Add a .prettierignore configuration file to tell your editor which files do not need to be formatted;
  • Format the entire project file by running npx prettier —write .
  • Check the format specification of each project file by running npx prettier —check .
  • Use eslint-config-prettier ensure that ESLint and Prettier work perfectly together;
  • Setting up a pre-commit hook ensures that every commit is formatted.

EditorConfig

What is EditorConfig

Official documentation: EditorConfig
Mainly used to maintain a consistent coding style for multiple developers working on the same project in multiple editors and IDEs. The EditorConfig project includes a file format for defining coding styles and a collection of text editor plugins that enable editors to read the file format and follow the defined styles.
EditorConfig and ESLint have different focuses. EditorConfig is more inclined to code style, defining and maintaining a consistent coding style. ESLint focuses on checking Javascript programming syntax errors, the two do not conflict, and they can make the code style more elegant when used together.

Recommended configuration

editorConfig configuration: .editorConfig file

# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
# 适用范围:跨编辑器和IDE编写代码,保持一致的简单编码风格

# 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

Prettier configuration: .prettierrc file

{
    "singleQuote": true,
    "semi": true,
    "arrowParens": "avoid",
    "bracketSpacing": true,
    "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
}

ESLint configuration: .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']
    }
};

VSCode editor extension plugin

  1. Prettier - Code formatter - Visual Studio Marketplace

    VSCode in prettier - Code Formatter plug-in settings detailed tutorial: GitHub - prettier / prettier-VSCode: Extension for Visual Studio Code prettier
  2. Vetur - Visual Studio Marketplace
  3. ESLint - Visual Studio Marketplace
  4. EditorConfig for VS Code - Visual Studio Marketplace

references

ESLint and Prettier - Know

I am a Paige cook, now living in Shanghai, a hard-working front-end siege lion who loves research, technology, and sharing.
Personal notes are not easy to organize. Thanks again for reading, liking, collecting and following!
If you have any questions about the article, please leave a message and point it out, and you are also welcome to exchange and learn together!

云鱼
3.2k 声望530 粉丝

感谢阅读、浏览和关注!