Prettier is a knowledgeable code formatting tool. It enforces a consistent style by parsing the code and reprinting it using its own rules, taking into account maximum lines, and wrapping the code when necessary. Today, it is the preferred solution for all code formatting problems; Supports JavaScript, Flow, TypeScript, CSS, SCSS, Less, JSX, Vue, GraphQL, JSON, Markdown, etc. You can combine ESLint with Prettier, While detecting potential problems in your code, you can also unify your team’s code style, which can lead to high quality code that increases productivity.

beautify-vue-by-eslint-and-prettier

Note, this article was first published in a new Web application built with Vuepress: Jing Qing Xuan Biyuan; If you’re interested, take a look: Beautify Vue code with ESLint & Prettier.

Initialize the Vue project recommendation

Prettier does overlap with ESLint in formatting code, but the emphasis is different: ESLint mainly checks code for quality and hints, and can provide very little formatting. Prettier has an even greater advantage in formatting code. Prettier is designed to integrate easily with ESLint, so you can easily have both in a project without worrying about conflicts. Here’s how to format and Prettier Vue code using ESLint & Prettier. If you use other types of frameworks, much of this experience still applies.

As advocated in the out-of-the-box Vue Webpack scaffolding template: VUE-CLI3 in this release, it integrates more rich features, as well as more default configurations, to create, develop and manage projects through the included GRAPHICAL user interface… The RC version has been released, the core functions are ready and the API is stable, so it is recommended to use VUE-CLI3 to create your project; Simply run the vue create my-project command and follow the prompts to select; ESlint is a necessary option for your project to continue happily. If you do, you can find the ESLint configuration under the eslintConfig property in package.json; Next, just integrate Prettier with ESLint.

Integrate ESLint & Prettier

For the integration of the two, plug-ins can be used to complete; Eslint plugin – prettier exposes a “it” configuration, the plugin: prettier/it added to the extends child attributes plugin: vue/essential, Prettier enable support for Prettier in ESLint with default:

"eslintConfig": {
    "root": true,
    "extends": [
      "plugin:vue/essential",
      "plugin:prettier/recommended",
      "eslint:recommended"
    ]
  },
Copy the code

Of course, you also need to install the dependency libraries eslint-plugin-prettier and eslint-config-prettier (where this dependency is used later), as shown in the documentation for prettier: Integrating with ESLint.

yarn add --dev eslint-plugin-prettier eslint-config-prettier prettier-eslint-cli
Copy the code

3, Eslint-plugin-prettier: Eslint-plugin-prettier compares code before prettier is formatted with code after prettier is formatted, and displays an error if there is inconsistency. There are tools to fix this: eslint –fix, prettier-eslint-cli; It can be configured in Package Scripts for easy use:

{
  "scripts": {
    "eslint-fix": "eslint src/**/**/*.vue --fix",
    "format-code": "prettier-eslint --write \"src/**/*.js\" \"src/**/*.vue\""
  }
}
Copy the code

beautify-vue-by-eslint-and-prettier

Modifying Rule Configuration

What you need to know is that when you mix the two, you need to change the rules to prevent duplication or conflict; Eslint-config-prettier shuts down conflicting rules eslint-config-prettier shuts down conflicting rules

"rules": {
  "prettier/prettier": "error"
}
Copy the code

In fact, when configured this way in a project, there may be some “weird” errors that cannot be resolved even with the above fixes; And this is not the prompt you expected;

Error: Delete ⏎ (prettier/prettier) at SRC /pages/ XXX

At this point, rules can be screened and sorted out to select the appropriate rules; For this, you can refer to Configuring Prettier Options & eslint-plugin-prettier# Options; According to personal coding habits, the following configuration is adopted (can be viewed at awesome-vue-cli3-example source code) :

"rules": {
  "no-console": 0,
  "prettier/prettier": [
    "error",
    {
      "singleQuote": true,
      "trailingComma": "none",
      "bracketSpacing": true,
      "jsxBracketSameLine": true,
      "parser": "flow"
    }
  ]
}
Copy the code

Add an editor configuration

The Atom editor

Prettier-atom can be installed; The Atom editor also prompts you to install more helper plug-ins;

apm install prettier-atom
Copy the code

It can be used in two modes:

  • (Packages → Prettier → Toggle Format on Save)
  • Manually called using the keyboard shortcut (if not selected, the entire file is formatted) :CTRL + ALT + F

VS Code editor

Preference → setting → User setting (shortcut key: Command +,) : ESlint, Prettier, VS Code

{
  "prettier.eslintIntegration": true,
  "eslint.autoFixOnSave": true,
  "editor.formatOnSave": true
}
Copy the code

Sublime Text editor

JsPrettier, which relies on Prettier, requires a global installation: YARN Global add Prettier; Add the following Settings in “Preferences → Setting” to realize automatic formatting when saving;

{
  "auto_format_on_save": true
}
Copy the code

Of course, you can also customize shortcuts to format code on demand; In the Preferences → Key Binding User Keymap, see the following example to inject the command (CTRL + Alt + F on Windows) :

{ "keys": ["command+alt+f"], "command": "js_prettier" }
Copy the code

See SublimeJsPrettier#Usage for more Settings and Usage details.

Pre-commit Hook Constrains code commit

Writing good code using ESLint & Prettier is recommended for individuals; In order for the team to have a uniform code style, some means must be taken to enforce constraints; If your team uses Git as a code management tool, it is a great choice to screen for constraints before and after commit actions. Husky & Lint-passage can be used to do this.

# install husky & lint-staged
yarn add lint-staged husky --dev

# package.json config
"lint-staged": {
  "**/**.{js,json,pcss,md,vue}": [
    "prettier --write",
    "git add"
  ]
},
"husky": {
  "hooks": {
    "pre-commit": "yarn run precommit-msg && lint-staged",
    "pre-push": "yarn test"
  }
},
Copy the code

It’s worth noting that on a real project, Husky probably wouldn’t work well for a variety of reasons; This is mostly due to.git/hooks/pre-commit not matching the desired target, you can either change it manually or do the following (note: if your husky version is 0.14 or higher) :

rm -rf .git/hooks/*
node node_modules/husky/lib/installer/bin install
Copy the code

Write it at the end of the article

“On evil, I want to know your friend, long life without absolute decline. Mountains without tombs, rivers are exhausted. Winter thunder earthquake, summer rain snow. Heaven and earth, but dare and king must.” This unexpected poem, at first sight, has nothing to do with this article. But a word of caution: the more effort you put into writing high-quality code, the less time you spend debugging. Do if you are working for the project development process, the sufficient and appropriate construction, which not only can greatly improve the code quality and speed, at the same time can save debugging, solve the problem of time overhead, but also can avoid gratuitous and a bad mood, so as to further promote the work efficiency, so make the quality of circulation, Can make you have more time to study, toss, taste life, which naturally can also include reading beautiful ancient poetry 🐉☺️; So? Have you learned that to do a good job, you must sharpen your tools?

@2018-06-15 in Shenzhen. Last Modify: 2018-06-15


Articles you may be interested in (/ useful) :

  • How to write a beautiful Vue
  • Webpack package optimization for speed
  • Webpack package optimized volume section
  • Npm VS Yarn Memo sheet
  • “Lead” the most complete front-end resource collection
  • Updated version of the front-end resources tutorial
  • The grass at night – Front notes
  • Replacement of the Experienced front end “Posture” (I)
  • Wall crack recommended article collection