Code style and configuration developed by the ESLint team

Coding style for team development

In a team developing the same project, each member's code style should be consistent.

For example:

① Strings in JS are represented by single quotes uniformly

② Code indentation, use two spaces uniformly

③ >2 consecutive blank lines are not allowed

④ At the end of the statement, a semicolon must be added

⑤ ......

Note that the above rules are not fixed. Just to illustrate, for example, my company's project requires a semicolon at the end of the statement, which is also possible.

It just means that the code style of a team should be unified.

How to ensure a uniform code style

Use the ESLint code inspection tool.

After using ESlint, programmers are forced to use the prescribed code style for development.

If the rules are violated, the code will report an error.

What is ESLint

Official concept: ESLint is a composable JavaScript and JSX linting tool.

Popular understanding: a tool to constrain the coding style of team members.

Official Website: ESLint - Pluggable JavaScript Code Inspection Tool - ESLint Chinese Documentation ESLint is a pluggable and configurable JavaScript syntax rule and code style inspection tool. ESLint can help you easily write high-quality JavaScript code https://eslint.bootcss.com/

What are the benefits of ESLint

Ensure that the written code style is consistent when the team collaborates on development.

How to use ESLint to check the code style in the project

After installing the project through the @vue/cli scaffolding tool, eslint has been installed and configured by default.

We will use the default rules stipulated by Vue's eslint plugin for code inspection. Note that it is not the official default rules of eslint.

If you need to modify the rules, you can check the official website .

Demonstrates how to configure ESlint

The two configurations shown below must be configured . It is related to the later vscode settings.

Regarding the configuration of ESLint, it needs to be placed in the configuration file.

Regarding the configuration file of ESLint, the official has detailed instructions, of course very detailed (Luo Suo)

For a project, ESLint configuration items:

  • Either put it .eslintrc.jsin ; if you use @vue/[email protected] to create a project like this
  • Either put it in the node package.jsonin eslintConfig; if you use @vue/cli5.0.x to create a project like this

Regardless of the above file, we find rulesthe node , this rulesnode is to configure ESLint rules

For example, if we configure the end of each statement without adding a semicolon, we need to add the following rules to rulesthe node :

"rules": {
  "semi": ["error", "never"]
}

The configuration file has been modified, and the project needs to be restarted (the terminal window needs to be restarted with npm run serve)

For example, to configure whether to add a space between "function name" and "parentheses", you need to rulesadd the following rules to the node:

"rules": {
  "space-before-function-paren": [
    "error",
    {
      "anonymous": "always",
      "named": "never",
      "asyncArrow": "always"
    }
  ]
}

The configuration file has been modified, and the project needs to be restarted (the terminal window needs to be restarted with npm run serve)

Explanation of the above rules:

"anonymous": "always"     匿名函数小括号前,需要空格。比如 setTimeout(function () {})
"named": "never"          有名字的方法,不需要空格。比如 abc() {}
"asyncArrow": "always"    箭头函数,需要空格。比如 aaaa(async data => {})

test

Open it src/App.vue, in the JS code, add a semicolon at the end of any statement, and try to see if there is an error message in the terminal or browser.

import HelloWorld from './components/HelloWorld.vue'
let a = 2
console.log(a); // 这里加了一个分号

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  methods: {
    add() {}
  }
}

 Remove the semicolon in the code and try again.

In this way, when writing code in the future, everyone must use a consistent code style.




vscode plugin configuration

Plugins that need to be installed and uninstalled
1. Plugins that need to be uninstalled
        ○JS-CSS-HTML Formatter
        ○Beautify
        ○There are other plugins for formatting code

uninstalled to avoid conflicts

2. Plugins that need to be installed

Plug-in installation summary

  • If you understand what your plugin does, you can just install the above plugin
  • If you don't understand what your plug-ins are for, then uninstall all the plug-ins and install the plug-ins shown in the figure below

Why do you need to install the ESLint plugin

Previous projects have used ESLint to check our code.

However, when writing code, it is inevitable to make "wrong" codes. It's not really wrong code, but it doesn't meet the requirements of the project.

This kind of "wrong writing", vscode did not prompt.

After installing the ESlint plug-in of vscode, when we "write wrong" code, vscode will give us a prompt.

After the plugin is installed, it needs to be configured. For configuration, see the later vscode plug-in configuration for details

Why do you need the Prettier formatted code plugin

Formatting the code is to automatically convert the badly formatted code into a format that meets the requirements.

The Prettier plug-in can be combined with ESLint.

In other words, the code formatted with Prettier just meets the requirements of ESlint.

After the plugin is installed, it needs to be configured. For configuration, see the later vscode plug-in configuration for details


Configure ESlint and Prettier plugins

Note that configuring ESlint here refers to a plugin called ESlint that configures vscode.

Open the vscode setting (shortcut key Ctrl + ,) to open the vscode setting interface.

Click the "Open Settings (json)" icon in the upper right corner of the settings interface:

After opening, you will see the code with the following structure:

Note that the structure is the same, because everyone's vscode settings have their own advantages, so the code is not necessarily the same.

{
    // =====================================================
    // 一会将代码复制到这里
    // =====================================================
    "workbench.iconTheme": "helium-icon-theme",
    "workbench.colorTheme": "laotang dark",
    "files.autoSave": "onFocusChange",
    "editor.fontFamily": "Menlo, 'Fira Code', 'FuraMono NF', Monaco, monospace, 'Courier New'",
    "editor.formatOnPaste": true,
    "editor.minimap.enabled": false,
    "[markdown]": {
        "editor.quickSuggestions": true
    }
}

Copy the configuration code below to the location specified above .

// prettier 的配置文件存放路径
"prettier.configPath": "C:\\Users\\xiafan\\.prettierrc",
// ---------------------------------------
// 路径提示
"path-intellisense.mappings": {
  "@": "${workspaceRoot}/src"
},
// ---------------------------------------
// 开启编辑器的保存自动格式化功能
"editor.formatOnSave": true,
// ESLint 插件的配置
"editor.codeActionsOnSave": {
  "source.fixAll": true
},
"eslint.alwaysShowStatus": true,
// ---------------------------------------
// 每行文字个数超出此限制将会被迫换行
"prettier.printWidth": 100,
// 使用单引号替换双引号
"prettier.singleQuote": true,
"prettier.arrowParens": "avoid",
"prettier.trailingComma": "none",
"prettier.semi": false,
// ---------------------------------------
// 设置 .vue 文件中,HTML代码的格式化插件
"vetur.format.defaultFormatter.html": "js-beautify-html",
// 忽略警告信息
"vetur.ignoreProjectWarning": true,
// 防止自动导入
"vetur.completion.autoImport": false,
// 不验证 .vue 组件的模板结构
"vetur.validation.template": false,
// vetur 默认的格式化配置项
"vetur.format.defaultFormatterOptions": {
  "prettier": {
    "trailingComma": "none",
    "semi": false,
    "singleQuote": true,
    "arrowParens": "avoid",
    "printWidth": 100
  },
  "js-beautify-html": {
    "wrap_attributes": false
  }
},
// ---------------------------------------
"[vue]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
  "editor.defaultFormatter": "vscode.html-language-features"
},
"[css]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"editor.tabSize": 2,

After copying, if there are duplicate configuration items, whether to keep the original configuration items or delete them depends on the specific configuration.

Configure Prettier

download configuration file

Download the following files:

Baidu network disk link: https://pan.baidu.com/s/1evelaVPEu0QWA9Rf1G_g-w 
Extraction code: lusj

After decompression, get .prettierrc.

put in the specified location

  • For Windows system, put .prettierrcthe file into C:/Users/你的用户名the folder (Users is the user).
  • On the Mac system, .prettierrcthe file is a hidden file, you need to press Command + Shift + .Show Hidden Files, then open the Finder, click Go on the top menu bar , open the personal (draw a small house icon) folder, and .prettierrccopy it to the personal folder.

Modify vscode settings

Modify the configuration file of vscode, and modify the path of the first configuration in the configuration

  • The Windows system is modified to"prettier.configPath": "C:\\Users\\LaoTang\\.prettierrc"
  • The Mac system is modified to"prettier.configPath": "~/.prettierrc"

Examples are as follows:

Configure the default formatter

Configure the default formatter for JS files and VUE files

Open any JS file, right mouse button, select "Format with...", in the menu that appears, select "Configure default formatter", select "Prettier - Code formatter"

Open any VUE file, right mouse button, select "Format with...", in the menu that appears, select "Configure default formatter", select "Prettier - Code formatter"

test

After this configuration.

When we write code, if the code format does not meet the requirements of ESLint, an error will be prompted;

When we save the code, if there is code that does not meet the requirements of ESLint, the Prettier plug-in will automatically format the code into one that meets the requirements

You can test it yourself.

 

 

Guess you like

Origin blog.csdn.net/m0_73089846/article/details/127889148