The original:Nice. Lovejade. Cn/useful/article /…

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.


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 Eslint-plugin-prettier It compares code before Prettier is formatted with code after Prettier is used, and displays an error if there is any 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


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": [
      "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 it can be used in two modes:

Automatic formatting (Packages → Prettier → Toggle Format on Save) manually called using 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

Prettier you also Prettier the Vscode editor according to your own preferences, see prettier-vscode for details.

"prettier.singleQuote": true."prettier.semi": false."prettier.tabWidth": 2."prettier.trailingComma": "none"
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”} In the same way, you Prettier the SublimeText editor for your own taste/taste; For more Settings and Usage details, see SublimeJsPrettier#Usage; Preferences → Package Settings → JsPrettier → settings-user

  "debug": false."prettier_cli_path": ""."node_path": ""."auto_format_on_save": false."auto_format_on_save_excludes": []."auto_format_on_save_requires_prettier_config": false."allow_inline_formatting": false."custom_file_extensions": []."max_file_size_limit": 1,"additional_cli_args": {},
  "prettier_options": {
    "printWidth": 80,
    "singleQuote": true."trailingComma": "none"."bracketSpacing": true."jsxBracketSameLine": false."parser": "babylon"."semi": false."requirePragma": false."proseWrap": "preserve"."arrowParens": "avoid"}}Copy the code

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