Abstract: Eslint solves the problem of code format checking, and has some useful tips for finding bugs and useless code (e.g
no-unused-vars, no-extra-bind, no-implicit-globals). However, ESLint doesn’t automatically beautify your code and make it uniform and well-formatted. EditorConfig addresses this in part by addressing issues such as code compaction and no Spaces at the end of lines, but it does too little to unify the style of the entire code. Prettier solves the rest of the problem by configuring the code we want, and then formatting/beautifying it with a script or editor plug-in.

Install and use

The installation

Select either global or local installation
npm install --save-dev prettier    # local
npm install --g prettier           # globalCopy the code

use

prettier [opts] [filename ...]
Example #
prettier --single-quote --trailing-comma es5 --write "{app,__{tests,mocks}__}/**/*.js"Copy the code

Editor Settings

Prettier is usually used in conjunction with an editor so that when we write code we can prettify it and see it in time. For example, sublime can be set like this:

1. Install the JsPrettier plug-in

Make sure prettier’s NPM package is already installed globally or locally.

  • ctrl/cmd + shift + pEnter the Install Package
  • Then type JsPrettier to find the package and install it

2. Use JsPrettier

CTRL/CMD + Shift + P Enter JsPrettier: Format Code.

Click to format the current file code.

Or set shortcut keys {“keys”: [“super+ Alt +f”], “command”: “js_prettier”}.

3. Write your own configuration file

If you do not write your own configuration file, the one that comes with the Sublime JsPrettier plug-in is generally used. We want to use the project’s own configuration file, where we can write the.prettierrc file in the project root. Prettier prettier looks for a configuration first in the.prettierrc file in the current directory and when not prettierrc looks in a higher directory until it is found or not.

The reference configuration

.prettierrc 

{
  "printWidth": 120, // Newline string threshold"semi": true// Add a semicolon at the end of the sentence"singleQuote": true// Use single quotes"trailingComma": "none"// Add a comma to the last object element"bracketSpacing": true, // Object, array, space"jsxBracketSameLine": false, // JSX > start a new line"arrowParens": "avoid", // (x) => {} whether to have parentheses"requirePragma": false, // Whether to comment to determine whether to format the code"proseWrap": "preserve"// Do you want a line break?Copy the code

Reference documentation

  • Formatting Code with Prettier
  • Prettier Options
  • react prettier script
  • sublime prettier package

Original author:
Passers-by are in a hurry

The original link