In team development, many people develop the same project. Due to different coding habits, the final code style in a project may vary greatly. Therefore, tools are needed to ensure the unity of code style. We also want tools to minimize the number of low-level errors and help fix them, so there are various lint and formatters.

The goal of this article is to use the vscode editor, the prettier plug-in, eslint to verify and correct code, and eslint-config-airbnb-base rules to unify the code style.

In general, our small company, small team may not have the ability and energy to formulate a set of detailed rules, so the use of large factory has formulated good rules is a very natural choice (at the same time, it is necessary to argue that your good or my good, the others are doing so, we will press the others to it! :))

Noun explanation

  • vscode

A text editor code.visualstudio.com/

  • prettier

Opinionated Code Formatter (Opinionated Code Formatter

  • eslint

The Pluggable Linting Utility for JavaScript and JSX

  • eslint-config-airbnb-base

A set of predefined ESLint rules, officially stated as: This package provides Airbnb’s base JS .eslintrc (without React plugins) as an extensible shared config.

Prettier, eslint, prettier, js and vue file verification to fix project code in the simplest way possible by using format of vscode to combine prettier with eslint to verify js and vue files

Vscode code Formatter function out of the box

Vscode provides out-of-box code styling (no CSS formatting). Create test files in the current folder:./ SRC /demo.html,./ SRC /fun.js,./ SRC /style.css, and the shortcut keys for formatting code are (win) : alt + shift + f

Before HTML formatting:


      
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Demo page</title>
</head>
<body><h1>This is a test page</h1>
<p>Page content</p>
</body>
</html>
Copy the code

After formatting:


      
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Demo page</title>
</head>

<body>
    <h1>This is a test page</h1>
    <p>Page content</p>
</body>

</html>
Copy the code

Before formatting:

function getUserInfo(name) {let HelloStr = "Hello, your name is: "
return HelloStr + name
}
Copy the code

After formatting:

function getUserInfo(name) {
    let HelloStr = "Hello, your name is: "
    return HelloStr + name
}
Copy the code

CSS:

As you can see, CSS files cannot be formatted by default, so it was Prettier’s turn

Format code with prettier

The official explanation for Prettier is:

  • An opinionated code formatter
  • Supports many languages
  • Integrates with most editors
  • Has few options

It can be combined with multiple editors to format multiple languages, so CSS is no problem.

Because vscode does formatting by default, prettier also does formatting when prettier is installed to cause conflicts (for HTML, js), where the editor tells you to configure it.

Vscode and Prettier have a lot of default Settings, which you can use CTRL + to go to the configuration screen and save in settings.json.

Where does the default formatter for vscode conflict with prettier, edit settings.json to the configuration file where the default formatter for vscode conflicts with prettier

{
    "[html]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[jsonc]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"}}Copy the code

You can also specify the formatter of all the files at once. The settings.json file is modified as follows:

{
    "editor.defaultFormatter": "esbenp.prettier-vscode"
}
Copy the code

After prettier, CSS and other types of files can be formatted by prettier.

Validates javascript code with ESLint

After the configuration above, you can format your code, but if you want to check and fix your code style, you need to use ESLint. Here are two steps to integrate ESLint functionality into your project:

  1. Install ESLint and related packages within your project
  2. Install the eslint plugin for vscode

So let’s do it separately

Install ESLint and related packages within your project

After the above operations, install esLint and related packages into the project as follows: package.json

{... "Dependencies" : {" eslint - plugin - vue ":" ^ 5.2.2 "}, "devDependencies" : {" eslint ":" ^ 5.16.0 "}... }Copy the code

The esLint configuration file.eslintrc.js is added to the project directory:

module.exports = {
    "env": {
        "browser": true."es6": true
    },
    "extends": [
        "eslint:recommended"."plugin:vue/essential"]."globals": {
        "Atomics": "readonly"."SharedArrayBuffer": "readonly"
    },
    "parserOptions": {
        "ecmaVersion": 2018."sourceType": "module"
    },
    "plugins": [
        "vue"]."rules": {}};Copy the code

The contents of this configuration file are automatically generated by NPX eslint –init, of course you can also configure it manually, all options are described here in Chinese: eslint.cn/docs/user-g…

Now you can perform the validation manually:

There may be a message indicating that the package is not installed during execution

Failed to load plugin vue: Cannot find module ‘eslint-plugin-vue’

The funs.js file contains an error indicating that the verification program is running properly.

The rule used is eslint:recommended, and our goal is to use ‘eslint-config-Airbnb-base’, so install the appropriate package:

npm i -D eslint-config-airbnb-base eslint-plugin-import
Copy the code

Then configure.eslintrc.js:

module.exports = {
  env: {
    browser: true.es6: true,},extends: 'airbnb-base'.globals: {
    Atomics: 'readonly'.SharedArrayBuffer: 'readonly',},parserOptions: {
    ecmaVersion: 2018.sourceType: 'module',},plugins: [
    'vue',].rules: {
    'linebreak-style': ["error"."windows"]}};Copy the code

Check again:

D:\works\secoo\test\code-formatter> npx eslint .\src\funs.js

D:\works\secoo\test\code-formatter\src\funs.js
  1:10  error  'getUserInfo' is defined but never used              no-unused-vars
  2:7   error  'HelloStr' is never reassigned. Use 'const' instead  prefer-const
  3:7   error  'age' is assigned a value but never used             no-unused-vars
  3:7   error  'age' is never reassigned. Use 'const'Instead prefer-const 3:15 error Missing Semicolon semi * 5 problems (5 errors, *) 0 warnings) 3 errors and 0 warnings potentially fixable with the `--fix` option.Copy the code

It can be seen that there are significantly more errors than before. Aribnb’s rules are relatively strict, which can avoid many low-level errors.

We added ‘linebreak style’: [“error”, “Windows “] to.eslintrc.js rules because different systems handle line breaks differently.

Install the eslint plugin for vscode

Js files are now ready to be verified, and a number of problems have been found, but there are no errors in vscode, so we use another vscode plugin, eslint. After installing the plugin, we can see an error in vscode:

Come here, we are very close to success!

Let Pretter style code based on esLint validation results

Up to now, it is possible to check js files, and even to repair js files according to the rules:

D:\works\secoo\test\code-formatter> npx eslint --fix .\src\funs.js

D:\works\secoo\test\code-formatter\src\funs.js
  1:10  error  'getUserInfo' is defined but never used   no-unused-vars
  3:9   error  'age'Is assigned a value but never used no-unused-vars disk (2 errors, 0 warnings)Copy the code

But if you fix it using vscode (where prettier is used) and find that Airbnb rules aren’t applied, you need to manually configure it:

  • CTRL + ,Open the Configuration page
  • Extension -> Prettier type Eslint Integration and check to get vscode configuration filesettings.jsonThe following
{
    "editor.defaultFormatter": "esbenp.prettier-vscode"."prettier.eslintIntegration": true
}
Copy the code

Then format the js file and execute it according to the specified rules. The specific operations are as follows:

Verify and format vUE code

This part is the most troublesome, many students are overturned here……

First of all, to understand the Vue file vscode, you need to install the plug-in vetur, basically install this plug-in can be happy with the vue code, vetur default configuration is as follows:

{
  "vetur.format.defaultFormatter.html": "prettyhtml"."vetur.format.defaultFormatter.css": "prettier"."vetur.format.defaultFormatter.postcss": "prettier"."vetur.format.defaultFormatter.scss": "prettier"."vetur.format.defaultFormatter.less": "prettier"."vetur.format.defaultFormatter.stylus": "stylus-supremacy"."vetur.format.defaultFormatter.js": "prettier"."vetur.format.defaultFormatter.ts": "prettier"
}
Copy the code

The above is the default configuration, which looks pretty good because you can format the code as follows:

A format command | | next | vetur received orders Will format the task over to prettier | | next | prettier received orders Will format the task over to eslint | | next | eslint receive the command, the code formatCopy the code

Prettier, not ESLint When formatting vue files prettier, not ESLint

If you want to format a VUE as described above, you need to do two things: settings.json

  • Prettier-eslint Set js formatter in vetur to prettier-eslint
{... "vetur.format.defaultFormatter.js": "prettier-eslint" ... }Copy the code
  • Prettier – eslint installation package
npm i -D prettier-eslint
Copy the code

Prettier-eslint prettier-esLint is pretty clear on the website for this problem:

This formats your code via prettier, and then passes the result of that to eslint –fix. This way you can get the benefits of prettier’s superior formatting capabilities, but also benefit from the configuration capabilities of eslint.

But there is such a problem, I read countless students around the Internet, indeed there will be two holes in the straight line understanding:

  1. Prettier already formats JS under ESLint. Vetur told Prettier it would be okay. Reality needs to be delivered toprettier-eslint
  2. Many students crossed the first hurdle, but never thought about itprettier-eslintNeed to manually install a package ah!

So I couldn’t go on at the last step.

So far, the configuration is complete. The results are as follows:

The final summary

To sum up, what is the total work that needs to be done

  1. Install the vscode plug-ineslint,prettier,vetur
  2. Configure esLint rules
  3. Configure prettier to work as esLint
  4. Configuration vetur

The final configuration file is as follows: settings.json

{
  "extensions.autoUpdate": false."eslint.validate": ["javascript"."javascriptreact"."vue"]."prettier.eslintIntegration": true."vetur.format.defaultFormatterOptions": {
    "prettier": {
      "eslintIntegration": true}},"vetur.format.defaultFormatter.js": "prettier-eslint"."[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[jsonc]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "vetur.format.defaultFormatter.html": "prettier"
}

Copy the code

.eslintrc.js

module.exports = {
  env: {
    browser: true.es6: true
  },
  extends: ['airbnb-base'.'plugin:vue/recommended'].globals: {
    Atomics: 'readonly'.SharedArrayBuffer: 'readonly'
  },
  parserOptions: {
    ecmaVersion: 2018.sourceType: 'module'
  },
  plugins: ['vue'].rules: {
    'linebreak-style': ['error'.'windows'].'comma-dangle': ['error'.'never'].// Fix an issue with eslint-plugin-vue}};Copy the code

The source code is here

Reference article:

  • Vetur official documentation
  • prettier-eslint github rep
  • eslint configuring
  • eslint rules
  • gitignore
  • Prettier Integrating with Linters
  • He Xing 的 blog
  • How I Resolved Vue.js, VSCode, Vetur, Prettyhtml, and Prettier Formatting and ES Lint Issues
  • Js-beautify Github rep and description

Tips

  • Due to bugs in the latest version of vetur, you need to roll back to version 0.18.1. For details, see github.com/vuejs/vetur…