preface

In teamwork, to avoid low-level bugs, as well as the confusion and influence caused by different code styles in teamwork. If there is no uniform specification in the project, it will lead to a variety of code styles, which is not conducive to code reading and maintenance. Therefore, a code specification is prepared in advance. Using Lint or code style checking tools can assist in the implementation of the code specification and effectively control code quality. EsLint is a good one.

EsLint, which you should be familiar with, is used to validate code specifications. Prettier is used to unify code style and format code, including JS, TS, CSS, LESS, SCSS, JSON, JSX. Also integrated with vscode, vim, webstorm, sublime text plug-ins.

EsLint provides the following support:

  • ES6
  • JSX
  • Style to check
  • Custom errors and prompts

EsLint provides the following validations:

  • Syntax error check
  • Unimportant or missing punctuation marks, e.g., semicolons;
  • Notification of unused parameters
  • Missing terminators, such as curly braces}
  • Ensure uniform rules for styles, such as sass or less
  • Check the naming of variables
  • Code alerts that affect performance, such as V-if and V-for used together

Best CP combination Eslint & Prettier

EsLint installation and configuration

Install EsLint globally

npm install -D eslint
Copy the code

Search the VSCode plugin market for ESLint, download and install it, as shown below:

The basic specification of this project is based on the official ESlint-plugin-vue. And uses Prettier to format code to conform to rules.

Add the.eslintrc.js file to the root directory of the project and add the following configuration:

module.exports = {
  root: true.// The current configuration is the root configuration and will no longer look up the configuration from the parent folder
  parserOptions: {
    parser: 'babel-eslint'.// Use babel-eslint as a syntax parser
    sourceType: 'module'  // Specify the type of source. There are two types of script or module
  },
  env: {
    browser: true.// The code set to check is running in the browser environment
    node: true.// The code to be checked is running in a nodeJS environment
    es6: true // Set the required check code to es6 syntax
  },
  // Configure the js global variable, since it is uni-app, the global UNI does not need to be introduced
  globals: {
    uni: 'readonly'.wx: 'readonly',},extends: ['plugin:vue/recommended'.'eslint:recommended'.'plugin:prettier/recommended'].// Extensions use vUE checking rules and ESLint recommendation rules
  rules: {
    'prettier/prettier': 'error'.'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off'.// Only development environments can use console
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'.// Only development environments can use the Debugger
    'vue/attribute-hyphenation': 0.// Ignore the attribute hyphen
    'vue/max-attributes-per-line': [2, { singleline: 10.multiline: { max: 1.allowFirstLine: false}}].// Maximum attributes per row
    'vue/singleline-html-element-content-newline': 'off'.// A single line of HTML element content on a new line
    'vue/multiline-html-element-content-newline': 'off'.// Multiple lines of HTML element content in a new line
    'vue/html-closing-bracket-newline': 'off'.// HTML close parenthesis on a new line
    'vue/no-v-html': 'off'.// Do not use V-html
    'vue/html-self-closing': 0.// Ignore HTML tag self-closing
    'accessor-pairs': 2.// Both setters and getters should be set
    'arrow-spacing': [2, { before: true.after: true}].// Arrow spacing
    'vue/require-default-prop': 0.// Do not check the default properties
    'vue/require-prop-types': 0.// Do not check the default type
    'block-spacing': [2.'always']./ / block spacing
    'brace-style': [2.'1tbs', { allowSingleLine: true}].// The brace style allows a single line
    'camelcase': [2, { properties: 'always'}].// Enforce a hump name for the attribute
    'comma-dangle': [2.'never'].// The comma does not use suspension
    'comma-spacing': [2, { before: false.after: true}].// comma spacing
    'comma-style': [2.'last'].// (default) commas are required after and on the same line as array elements, object attributes, or variable declarations
    'constructor-super': 2.'consistent-this': [2.'that'].// Force this to alias that
    'curly': [2.'multi-line'].// When a block contains only one statement, it is not allowed to omit curly braces.
    'dot-location': [2.'property'].// The dot in the member expression should be on the same line as the attribute section
    'eol-last': 2.// Force file to end with newline (LF)
    'eqeqeq': ['error'.'always', { null: 'ignore'}].// enforce congruence
    'generator-star-spacing': [2, { before: true.after: true}].// Both sides of the '*' in the generator should be spaced
    'global-require': 1.// All calls to require() are at the top level of the module
    'indent': [2.2, { SwitchCase: 2}].// Indent style
    'key-spacing': [2, { beforeColon: false.afterColon: true}].Enforces a consistent spacing between keys and values in object literal attributes
    'keyword-spacing': [2, { before: true.after: true}].// Spacing for keywords such as if/function, etc
    'new-cap': [2, { newIsCap: true.capIsNew: false}].// Allow calling a function started in uppercase without the new operator; The (default) requires new to invoke all operators using uppercase start functions
    'new-parens': 2.// JavaScript allows you to omit parentheses when calling a function with the new keyword
    'no-array-constructor': 1.Array constructors are not allowed. Unless you want to specify the length of the generated array
    'no-class-assign': 2.// Class declared variables are not allowed to be modified
    'no-const-assign': 2.// Variables declared with the const keyword cannot be modified
    'no-control-regex': 0.// Control characters in regular expressions are not allowed
    'no-delete-var': 2.// The delete operator is not allowed on variables
    'no-dupe-args': 2.// Duplicate parameter names are not allowed in function declarations or expressions
    'no-dupe-class-members': 2.// Duplicate parameter names are not allowed in class members
    'no-dupe-keys': 2.// Duplicate keys are not allowed in object text
    'no-duplicate-case': 2.// Duplicate test expressions are not allowed in case clauses of switch statements
    'no-empty-character-class': 2.// Null-character classes are not allowed in regular expressions
    'no-empty-pattern': 2.// Empty block statements are not allowed
    'no-eval': 2.// Eval is not allowed
    'no-ex-assign': 2.// Reassigning exceptions in catch clauses is not allowed
    'no-extend-native': 2.// It is not allowed to modify the prototype of the built-in object directly
    'no-extra-boolean-cast': 2.// Disable unnecessary Boolean conversions
    'no-extra-parens': [2.'functions'].Disallow unnecessary parentheses only around function expressions
    'no-fallthrough': 2.// Eliminate one case accidentally dropped into another case
    'no-floating-decimal': 2.// Eliminates the floating-point point and warns if a value has a decimal point but is missing before or after it
    'no-func-assign': 2.// Allow reassignment of function declarations
    'no-implied-eval': 2.// Remove the implied eval()
    'no-inner-declarations': [2.'functions'].// declarations in function nested blocks are not allowed
    'no-invalid-regexp': 2.// Invalid regular expression strings in RegExp constructors are not allowed
    'no-irregular-whitespace': 2.// Catch invalid Spaces
    'no-iterator': 2.// Eliminate shadow variable declarations
    'no-label-var': 2.// Disallows the creation of tags that share names with variables in the scope
    'no-labels': [2, { allowLoop: false.allowSwitch: false}].// Eliminate the use of tagged statements in JavaScript
    'no-lone-blocks': 2.// Eliminate unnecessary and potentially confusing blocks at the top level of the script or other blocks
    'no-mixed-spaces-and-tabs': 2.// Indent with mixed Spaces and tabs is not allowed
    'no-multi-spaces': 2.Disallow multiple Spaces around logical expressions, conditional expressions, declarations, array elements, object attributes, sequences, and function arguments
    'no-multi-str': 2.// Prevent multi-line strings
    'no-multiple-empty-lines': [2, { max: 1}].// At most one blank line
    'no-native-reassign': 2.// Read-only global variables are not allowed to be modified
    'no-new-object': 2.// The Object constructor is not allowed
    'no-new-require': 2.// Eliminate the use of the new require expression
    'no-new-symbol': 2.// Prevent accidental errors when Symbol is used with new
    'no-new-wrappers': 2.// Eliminate String, Number, Boolean and new operations
    'no-obj-calls': 2.Math, JSON, and Reflect objects are not allowed to be called as functions
    'no-octal': 2.// Octal characters are not allowed
    'no-octal-escape': 2.// Octal escape sequences in string literals are not allowed
    'no-path-concat': 2.// Prevent directory path string concatenation in Node.js from being invalid
    'no-redeclare': 2.// Eliminate variables with multiple declarations in the same scope
    'no-regex-spaces': 2.// Multiple Spaces are not allowed in regular expression text
    'no-return-assign': [2.'except-parens'].// Eliminate tasks in the return statement unless enclosed in parentheses
    'no-self-assign': 2.// Eliminate self-assignment
    'no-self-compare': 2.// Disallow comparing variables with themselves
    'no-sequences': 2.// Disallow the comma operator
    'no-sparse-arrays': 2.// Sparse array literals are not allowed
    'no-this-before-super': 2.// Mark this/super keyword super() before calling
    'no-throw-literal': 2.// It is not allowed to throw literal and other expressions that cannot be Error objects
    'no-trailing-spaces': 2.Trailing whitespace is not allowed at the end of the line
    'no-undef': 2.// Any reference to an undeclared variable results in an error
    'no-undef-init': 2.// Eliminate variable declarations initialized to undefined
    'no-underscore-dangle': 2.// Identifiers cannot start or end with an _
    'no-unexpected-multiline': 2.// It is not allowed to confuse multi-line expressions
    'no-unmodified-loop-condition': 2.// Look for references within the loop condition, and then check whether the referenced variables are modified in the loop
    'no-unneeded-ternary': [2, { defaultAssignment: false}].// Conditional expressions are not allowed as the default allocation mode
    'no-unreachable': 2.Return, throw, continue, and break statements are followed by statements.
    'no-unsafe-finally': 2.// Finally blocks in return, throw, break, and continue are not allowed
    'no-unused-vars': [2, { vars: 'all'.args: 'after-used'}].// Eliminate unused variables, functions, and function arguments
    // vars: 'all' checks the use of all variables, including global-scoped ones. This is the default setting. Args: 'after-used' only the last parameter must be used. For example, this allows you to use two named arguments for functions, and ESLint will not warn you about the first argument as long as you use the second argument. This is the default setting.
    'no-useless-call': 2.// flag usage, function.prototype.call () and function.prototype.apply () can be replaced with normal Function calls
    'no-useless-computed-key': 2.// Disallow unnecessary use of computed property keys
    'no-useless-constructor': 2.// A class constructor that can be safely removed without changing the way the class works
    'no-useless-escape': 0.// Disable unnecessary escape characters
    'no-whitespace-before-property': 2.If the attributes of the object are on the same line, no space is allowed around the dot or before the opening parenthesis
    'no-with': 2./ / disable the with
    'no-var': 2./ / disable var
    'one-var': [2, { initialized: 'never'}].// Forces variables to be declared together or separately for each function (for var) or block (for let and const) scope. Initialized: 'never' requires multiple variable declarations per scope to initialize variables
    'operator-linebreak': [2.'after', { overrides: { '? ': 'before'.':': 'before'}}].// implement consistent line breaks
    'padded-blocks': [2.'never'].// Enforce consistent blank line padding within the block
    'prefer-destructuring': ['error', { object: false.array: false}].// This rule enforces the use of destructuring instead of accessing attributes through member expressions.
    'quotes': [2.'single', { avoidEscape: true.allowTemplateLiterals: true}].// avoidEscape: true allows strings to use single or double quotes, as long as the string contains quotes that must otherwise be escaped; AllowTemplateLiterals: true allows strings to use backquotes
    'radix': 2.// parseInt must specify a second argument
    'semi': [2.'never'].// Do not use semicolons
    'semi-spacing': [2, { before: false.after: true}].// Enforce semicolon spacing
    'space-before-blocks': [2.'always'].// The block must have at least one previous space
    'space-before-function-paren': [2.'never'].// No Spaces are allowed after the (argument
    'space-in-parens': [2.'never'].// Disallow or require (or require) one or more Spaces to the left
    'space-infix-ops': 2.// Enforces a space to the left and right of the binary operator
    'space-unary-ops': [2, { words: true.nonwords: false}].// words: true such as new, delete, typeof, void, yield must have Spaces // nonwords: false Unary operators such as -, +, --, ++,! ,!!!!! No Spaces left or right
    'spaced-comment': [2.'always', { markers: ['global'.'globals'.'eslint'.'eslint-disable'.'*package'.'! '.', ']}],// This rule enforces consistency of spacing // or /* after comments begin
    'template-curly-spacing': [2.'never'].// Spaces in braces are not allowed
    'use-isnan': 2.// Disallow NaN for comparison, only isNaN()
    'valid-typeof': 2.// Must use valid Typeof values
    'wrap-iife': [2.'any'].// Execute function expressions immediately in parenthesis style
    'yield-star-spacing': [2.'both'].// Enforces the spacing of the yield* expression around *, with Spaces on both sides
    'yoda': [2.'never'].'prefer-const': 2.// A variable declared with the let keyword, but never reassigned after the initial allocation, should be declared const
    'object-curly-spacing': [2.'always', { objectsInObjects: false}].// The spacing inside curly braces of objects that begin and/or end with object elements is not allowed
    'array-bracket-spacing': [2.'never'] // Array parenthesis Spaces are not allowed}}Copy the code

Prettier Installation and configuration

Installing Prettier globally

npm install -D prettier
Copy the code

Search prettier for THE VScode plug-in market, download and install it as shown below:

Create the.prettierrc.json file in the root directory of the project and add the following configuration:

{
  "printWidth": 175.// Length per line (default 175)
  "trailingComma": "none".// Whether to place a comma after the last element of an object or array
  "tabWidth": 2.// How many Spaces per TAB (default: 2)
  "useTabs": true.// Use TAB to indent instead of Spaces
  "semi": false.// Whether to add a semicolon to the end of the line
  "singleQuote": true.// Use single quotes instead of double quotes
  "arrowParens": "avoid".// (x) => {} arrow function with only one argument whether to have parentheses. Avoid: omit parentheses
  "bracketSpacing": true.// Add a space between the object, array bracket and text "{foo: bar}"
  "proseWrap": "preserve".// Default value. Folds markdown text style due to the use of some fold-sensitive renderer (such as GitHub Comment)
  "htmlWhitespaceSensitivity": "ignore".// HTML file space sensitivity
  "jsxBracketSameLine": true  // Place > multi-line JSX elements at the end of the last line, rather than on the next line alone
}
Copy the code

The verification file was ignored

Create a new.eslintignore file in the project root directory and add the following configuration:

node_modules
src/assets
build
public
dist
Copy the code

Vscode editor configuration

Find the.vscode folder in the project root directory. If you don’t have one, create a new settings.json file and add the following configuration:

{
  "editor.tabSize": 2."editor.formatOnSave": true.// Automatic formatting when saving
  "editor.wordWrap": "on"."vetur.format.defaultFormatter.html": "js-beautify-html".// Because prettier cannot format the vue template, js-beautify- HTML is used
  "vetur.format.defaultFormatterOptions": {"js-beautify-html": {"wrap_attributes":"auto"}},/* EsLint configuration */
  "eslint.enable": true."eslint.run": "onSave"."eslint.options": {
    "extensions": [
     ".js".".vue"]},"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true // Automatic repair when saving
   },
   // close vscode's default checker
   "html.validate.scripts": false."javascript.validate.enable": false."eslint.alwaysShowStatus": true."eslint.format.enable": true."scss.lint.duplicateProperties": "error"."css.lint.duplicateProperties": "error"."less.lint.zeroUnits": "error"."eslint.validate": [ // Verify the file type
    "javascript"."javascriptreact"."vue-html"."vue"."html"]}Copy the code

Do not select the Lint option when creating a project using vue-CLI scaffolding.

Add babel-eslint, eslint, eslint-plugin-vue, prettier, eslint-plugin-prettier, eslint-config-prettier dependency to the dependency babel-eslint, eslint, eslint-plugin-vue, prettier, eslint-plugin-prettier, eslint-config-prettier

NPM install babel-eslint eslint eslint-plugin-vue prettier eslint-plugin-prettier eslint-config-prettier -d NPM install babel-eslint eslint-plugin-vue prettier eslint-plugin-prettier eslint-config-prettier -dCopy the code

When you save the file during development, you can format the file according to the rule prettier, and automatically repair repairable issues. If not, manually repair them as prompted.

Tip: vscode has been set to format on save, but sometimes files are not formatted. If an error occurs in the saved file, manually format the file, correct the error, and save the file again.

conclusion

Okay, so that’s it. It’s a couple of simple steps. It shouldn’t take too long. If you are a strict code cleanliness freak or if you have a code writing requirement for your front-end team, use it.

If there are any mistakes in this article, please correct them in the comments section. If this article helps you, please give a thumbs up to show your encouragement.