Unified front-end code style

Code format problems usually refer to: single line code length, TAB length, Spaces, comma expressions, etc. Code quality issues are: unused variables, equal signs, global variable declarations, etc.

Objective: To ensure that every student code style always. Edit save automatically formats code, and the editor can prompt some common errors

Using STAR model collation, project github

why

Development problems caused by differences in code styles, editors, and Settings, resulting in inconsistent code styles

task

  1. Figure out what can be configured?
  2. What does a configuration item do?
  3. How can conflicts be resolved?
  4. Configure a uniform code style for later configuration use

action

This section describes configurable items

Because some software functions are too powerful, we only talk about the functions related to our blog

vscode

  • Vscode automatically formats code
  • Vscode automatically formats the configuration

Vscode vuter plug-in

  • website
  • Syntax error checking, including CSS/SCSS/LESS/Javascript/TypeScript
  • Syntax highlighting, including HTML/jade/CSS/sass SCSS relation/less/stylus js/ts
  • Emmet support
  • Code completion (or primary stage at present, including HTML/CSS/SCSS/LESS/JavaScript/TypeScript
  • The formatter can be set in the vuter item in vscode, or the. Prettierrc file can be read to format

eslint

  • website
  • Fully configurable javascript code checking tool
  • Eslintrc.* file. Eslintrc. js file configuration, package.json can also be configured with the eslintConfig property
  • Eslint rules Configures rules
  • .eslintignore Ignore the verified files and directories, or read eslintignore in package.json. The package.json file also contains eslintignore files for configuration, and the. Eslintignore file configuration is preferred

vscode eslint PK npm eslint

  • Eslint in vscode is a reminder for when you code in your editor that doesn’t conform to the eslint specification. Eslint in NPM is used to verify that code complies with the ESLint specification when packaging webpack
  • Vscode eslint and NPM eslint read.eslintrc.js configuration files to generate rules

prettier

  • website
  • Address style differences, editor differences, and Settings differences, leaving only necessary Settings open
  • Read the prettier property in. Prettierrc,. Prettier.config. js, and package.json

Vscode Prettier – Code Formatter plug-in

  • A program that formats the code prettier, reads the. Prettierrc file, configures the document

lint-staged

  • Lint – staged
  • Lint checks once every time a file is modified

.vscode/settings.json

  • Save the current workspace configuration and apply different vscode configurations to different projects

. Editorconfig file

  • Helps maintain consistent coding styles across different editors and ides

Configuration items conflict with each other

Git diff can be set with multiple configuration items to edit, save and format the code. Inconsistency of each rule may lead to conflicts between the saved format and ESLint

Idea: Based on the latitude of the project to do the code style unified, not limited to the editor and plug-in. Try to achieve a set of configuration, the development of the simplest unified specification of the configuration

Project configuration

Prettier formatting code is used, ESLint verifies code quality, Lint-staged code is verified by ESLint and hot fixes, HusKY enhances commit and push code quality, and TS verifies code using ESLint


Editor configuration

  • Vscode removes the Format On Paste and Format On Save configurations to ensure that we go through the project formatter
  • Add vscode vuter plug-in (no other configuration in the editor)
  • Add vscode eslint plugins (no configuration in the editor)

Added configuration file

  • Add the. Prettierrc file, where the goal is to maintain a uniform format
{// TAB indent size, default is 2 "tabWidth": 2, // use semicolon, default is true "semi": false, // use single quotation marks, default is false(JSX configuration is invalid, default is double quotation marks) "singleQuote": // Always use parentheses to avoid arrow function 'arrowParens' : "Get", / / method insert space between the parentheses "javascript. The format. InsertSpaceBeforeFunctionParenthesis" : True, / / let the vue js according to the editor's own ts format to format "vetur. Format. DefaultFormatter. Js" : "vscode - typescript, / / wrapping length" printWidth ": 140, // Use TAB instead of space "useTabs": false}Copy the code
  • Add.eslintrc.js file, the goal is to prompt some simple errors
Module. exports = {// eslint specifies the current specific project root: true, // global variables env: {es6: true, node: true }, // plugin:vue/essential uses eslint-plugin-vue // @vue/prettier uses @vue/eslint-config-prettier // @vue/typescript Using the @ vue/eslint - config - typescript extends: ['plugin:vue/essential', '@vue/prettier', '@vue/typescript'], {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the compulsory style -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / disable the console 'no - the console: process.env.NODE_ENV === 'production' ? 'error' : 'off', // Disable debugger' no-debugger': process.env.node_env === 'production'? 'error' : 'off', // Requires or disallows the trailing comma 'comma-dangle': [2, 'never'], // enforces consistent space 'comma-spacing' before and after commas: 0, // Requires that arrow functions use parentheses 'arrow-parens': 0, // variables can only use 'block-scoped-var': 'error' in their scope, // constructors begin with a capital 'new-cap': ['error', {capIsNew: false}], 'no-tabs': 'off', // No duplicate names 'no-dupe-class-members' are allowed in class members: 'error', // disallows if statements as the only statements in else blocks 'no-lonely-if': 'error', // disallows nested ternary expressions 'no-nested-ternary': 'error', // disable new Symbol() 'no-new-symbol': 'off', // disable octal literal 'no-octal': 'error', // disable redeclare variable 'no-redeclare': Typeof x === 'number' && isNaN(x)) 'no-self-compare': 'error', // keywords cannot be Shadowed 'no-shadow-restricted-names': 'error', // disallow variable 'no-use-before-define' before definition: ['error', {functions: false, classes: false}], // disallow var (let or const) 'no-var': 'error', // disallow the void operator 'no-void': 'error', // disallow the with statement 'no-with': 'error', // use single quotes, strings can be quotes: ['error', 'single', { avoidEscape: true, allowTemplateLiterals: True}], / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- suggested style -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / requires the use of = = = and! == eqeqeq: ['warn', 'always', {null: 'ignore'}], // Enforces the maximum nesting depth of callback functions 'max-nested-callbacks': [' warn, 10], / / limits maximum number of parameters' Max - params: [' warn, 10], / / remind empty blocks' no - empty: 'WARN ', // disallow unnecessary Boolean conversions' no-extra-Boolean-cast ':' WARN ', // suggest that the conditional expression 'no-unneeded-ternary' can be expressed as a simpler construct: 'WARN ', // warn unused variables 'no-unused-vars': 'warn', // avoid unnecessary.call() and.apply() 'no-useless-call': 'WARN ', // Avoid unnecessary character concatenation 'no-useless-concat': 'warn', // avoid unnecessary escape' no-useless-escape': 'warn'}, // TS parsers parserOptions: { parser: '@typescript-eslint/parser' } }Copy the code
  • Add the. Editorconfig file (which comes with project initialization) with the goal of maintaining a uniform style across different editors
[*] charset=utf-8 end_of_line=lf insert_final_newline=false indent_style=space indent_size=2 [{*.ng,*.sht,*.html,*.shtm,*.shtml,*.htm}] indent_style=space indent_size=2 [{*.jhm,*.xslt,*.xul,*.rng,*.xsl,*.xsd,*.ant,*.tld,*.fxml,*.jrxml,*.xml,*.jnlp,*.wsdl}] indent_style=space indent_size=2  [{.babelrc,.stylelintrc,jest.config,.eslintrc,.prettierrc,*.json,*.jsb3,*.jsb2,*.bowerrc}] indent_style=space indent_size=2 [*.svg] indent_style=space indent_size=2 [*.js.map] indent_style=space indent_size=2 [*.less] indent_style=space indent_size=2 [*.vue] indent_style=space indent_size=2 [{.analysis_options,*.yml,*.yaml}] indent_style=space indent_size=2Copy the code
  • Add husky to package.json file to prevent illegal commit and push
"husky": {
  "hooks": {
    "pre-commit": "lint-staged"
  }
},
"lint-staged": {
  "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
    "eslint --fix"
  ]
}
Copy the code

You need to add “eslint. AutoFixOnSave “: true in vscode, otherwise saving code may not be eslint –fix

{
  "eslint.autoFixOnSave": true,
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    {
      "language": "html",
      "autoFix": true
    },
    {
      "language": "vue",
      "autoFix": true
    }
  ]
}
Copy the code

NPM plug-in used

  • Eslint recognizes js/ ES code specifications and error-checking tools
  • Babel-eslint parses ESLint rules
  • Eslint plugin-vue EsLint plugin- Vue
  • @vue/cli-plugin-eslint Mainly injects the command vue-cli-service lint. Eslintrc or package.json eslintConfig
  • Prettier Solves style differences, editor differences, Settings, open necessary Settings
  • @vue/eslint-config-prettier Disables the formatting rule for code that conflicts with Prettier in ESLint
  • Eslint-plugin-prettier You can configure the prettier rule as the rule of ESLint to prompt those who do not conform to the rule. (Same as eslint-plugin-vue)
  • Lint-staged errors can be fixed by having lint checked every time a file is modified
  • @vue/eslint-config-standard vue-CLI use, not external use, some extensions to eslint-plugin-vue
  • Eslint-plugin-standard EsLint can be configured to supplement standard rules
  • Husky Git commit triggers the hook function to validate the rule and prevent illegal commit and push attempts
  • @typescript-eslint/parser Validates typescript with ESLint rules
  • The @typescript-eslint/eslint-plugin provides Lint rules for typescript

The resulting

  • You learned some of the relationships between editors, plug-ins, and NPM packages
  • Knowing the general flow of a unified front-end code style, the project can then follow this line of thinking
  • .eslintrc.js rules can be studied in more detail, and can be better alarm during development
  • Importance of Documentation

More front-end specifications

  • Tencent Front-end specification
  • Jd front-end Specifications
  • W3cschool front-end specification
  • Baidu EFE front end specification

Refer to the link

  • Segmentfault.com/a/119000001…
  • Segmentfault.com/a/119000002…
  • Juejin. Cn/post / 684490…
  • zhuanlan.zhihu.com/p/68026905