Prettier

This article is based on the official website translation, if there are mistakes, welcome to correct

Introduction to the

Prettier is a code formatting tool that contains a large number of inherent specifications, supporting various front-end development languages, Markdown, YAML, and it can ensure the consistency of code rendering.

Why use Prettier?

“The most important reason for using Prettier is to stop arguing about code style,” Prettier says on its website. Indeed, having a common code style guide within a team or project is a very valuable thing. But trying to artificially control the style of your code is painful and not worth it. Therefore, Prettier is needed to help us achieve the unity of code style, because it automatically helps us to change the code format.

The difference between “Prettier” and “Linters”

Linters (ESLint/TSLint, etc.) mainly contain 2 types of rules:

  • Code style rules

    “Prettier” can be used to check whether the code style conforms to the convention, but it does not automatically compose the code. Prettier uses the convention to compose the code automatically. So after “Prettier” was used, most of these rules were no longer needed.

  • Code quality rules

    “Prettier” can help us check grammar mistakes, spelling mistakes, and avoid real bugs, but an Prettier cannot help “Prettier”.

Linters can be seen clearly. “Linters” can be used to check code specifications and grammar errors. “Prettier” can be used to check code style and layout, so the use of “Linters” can be very effective.

Natural style

Prettier has very few configuration items and cannot be added.

The code formatting specifications Prettier provides are not arbitrary or fully configurable, but mostly built-in code specifications. Since it was originally designed to stop the debate over code style, it is not completely free, but the code formatting specification it provides has passed the research phase and is a mature enough solution to be adopted by many large organizations and projects.

use

Installing a plug-in

Install using NPM

npm install --save-dev --save-exact prettier
Copy the code

Installation using YARN

yarn add --dev --exact prettier
Copy the code

Creating a Configuration file

Create the.prettierrc.json file in the root directory of the project

{}
Copy the code

Create ignore file

Create the.prettierIgnore file in the project root directory

Tip! Base your .prettierignore on .gitignore and .eslintignore (if you have one).

The sample

# Ignore a file type: *.htmlCopy the code

Formatting is ignored in single files

JavaScript

// prettier-ignore
matrix(
  1.0.0.0.1.0.0.0.1
)
Copy the code

JSX

<div>
  {/* prettier-ignore */}
  <span     ugly  format=' '   />
</div>
Copy the code

HTML

<! -- prettier-ignore -->
<div         class="x"       >hello world</div            >

<! -- prettier-ignore-attribute -->
<div
  (mousedown) =" onStart ( ) "
  (mouseup) =" onEnd ( ) "
></div>

<! -- prettier-ignore-attribute (mouseup) -->
<div
  (mousedown) ="onStart()"
  (mouseup) =" onEnd ( ) "
></div>
Copy the code

CSS

/* prettier-ignore */
.my    ugly rule
{

}
Copy the code

Markdown

<! -- prettier-ignore --> Do not format thisCopy the code

Multi-line ignore

<! -- prettier-ignore-start --> <! -- prettier-ignore-end -->Copy the code

Use the command line format

Format all files

// npm
npx prettier --write .
// yarn
yarn prettier --write .
Copy the code

Format folders

// npm
npx prettier --write app/
// yarn
yarn prettier --write app/

Copy the code

Format file

// npm
npx prettier --write app/components/Button.js
// yarn
yarn prettier --write app/components/Button.js
//
yarn prettier --write "app/**/*.test.js"

Copy the code

Check whether the file is formatted

// npm
npx prettier --check .

// yarn
yarn prettier --check .
Copy the code

The –check command only checks the files that have been formatted, not overwrites them.

–write will automatically check and typeset.

Editor integration

The most common way to use Prettier is to integrate Prettier into an editor. For details on the integration mode, see the extension/plug-in usage instructions for each editor.

Attention! The Prettier plug-in needs to be installed in every project to make sure they are in the correct version.

VSCode extension download Prettier – Code Formatter

ESLint

If you’re using ESlint, installing the eslint-config-prettier plugin for prettier ensures that ESlint and prettier work perfectly together. This plugin disables unnecessary or conflicting ESlint rules for prettier.

Similarly, if you use Stylelint, you can install the stylelint-config-prettier plug-in.

Other plug-in view document Integrating with Linters

Pre-commit Hook

Prettier can also be used for pre-commit. For details on how to use Prettier, see pre-commit Hook

Configuration items

Print Width

Specifies the length of the code line feed. The default is 80 characters.

For readability, the official recommendation is no more than 80 characters.

Default CLI Override API Override
80 --print-width <int> printWidth: <int>

Tab Width

Specifies the length of the indent, which defaults to 2.

Default CLI Override API Override
2 --tab-width <int> tabWidth: <int>

Tabs

Specifies how to indent: space or Tab. The default is false, indenting with space.

Default CLI Override API Override
false --use-tabs useTabs: <bool>

Semicolons

Specifies whether to use a semicolon at the end of the statement.

Default CLI Override API Override
true --no-semi semi: <bool>

Quotes

Use single quotes instead of double quotes.

JSX quotes ignore this rule.

Default CLI Override API Override
false --single-quote singleQuote: <bool>

Quote

Object attributes need to be quoted. Default is as-needed

  • "as-needed"– Attributes of an object are added only when they need to be quoted
  • "consistent"– Whenever an object property needs to be quoted, it is quoted
  • "preserve"– Save as is
Default CLI Override API Override
"as-needed" `–quote-props <as-needed consistent

Note that in Vue, Angular, TypeScript, and Flow statements, Prettier does not quote attributes of numeric type

JSX Quotes

Use single quotes instead of double quotes in JSX. The default is false

Default CLI Override API Override
false --jsx-single-quote jsxSingleQuote: <bool>

Trailing Commas

The comma at the end of the element. The default for es5

In the following example, the comma after the last element of the array is already the comma after the last attribute of the object.

Const array = [1, 2, 3]; cosnt object = { name: 'cat', age: 3, }Copy the code
  • "es5"-Commas are added to objects and Arrays in ES5, but not to type in TypeScript
  • "none"– does not add a comma
  • "all"– Always add commas, including for function arguments
Default CLI Override API Override
"es5" `–trailing-comma <es5 none

Bracket Spacing

Object. Defaults to True

  • true– such as:{ foo: bar }
  • false– such as:{foo: bar}
Default CLI Override API Override
true --no-bracket-spacing bracketSpacing: <bool>

JSX Brackets

Place the > following the HTML start tag at the end of the last line, rather than on a single line.

The default is false, which is a single line

  • true– such as:
<button
  className="prettier-class"
  onClick={this.handleClick}>
  Click Here
</button>
Copy the code
  • false– such as:
<button
  className="prettier-class"
  onClick={this.handleClick}
>
  Click Here
</button>
Copy the code
Default CLI Override API Override
false --jsx-bracket-same-line jsxBracketSameLine: <bool>

Arrow Function Parentheses

Whether to use parentheses when the arrow function takes only one argument. Default: always.

Parentheses are useful for adding type comments, extending parameters, or setting parameter defaults

  • "always"– such as:(x) => x
  • "avoid"– such as:x => x
Default CLI Override API Override
"always" `–arrow-parens <always avoid>`

Range

Formats only a section of code in a file

Default CLI Override API Override
0 --range-start <int> rangeStart: <int>
Infinity --range-end <int> rangeEnd: <int>

Parser

Specifies the parser to format the code. Prettier automatically deduces the parser based on the file type and usually does not need to be specified. Parser

File Path

Specifies the name of the file used to infer which parser to use

This configuration item takes effect only on the CLI and API. It is invalid in the configuration file

Require Pragma

Specify compilation directives: format only files that contain specific comments at the top of the file.

This is useful when you need to format a large project step by step.

The default is fasle. When set to true, files that use the following two comments will be formatted.

/**
 * @prettier
 */
Copy the code
/**
 * @format
 */
Copy the code
Default CLI Override API Override
false --require-pragma requirePragma: <bool>

Insert Pragma

Insert compilation indication: After the file has been formatted by Prettier, a special @format flag is inserted at the top of the file.

Default CLI Override API Override
false --insert-pragma insertPragma: <bool>

Prose Wrap

Prose Wrap

By default, Prettier will wrap markdown text as-is since some services use a linebreak-sensitive renderer, e.g. GitHub comment and BitBucket. In some cases you may want to rely on editor/viewer soft wrapping instead, so this option allows you to opt out with "never".

  • "always" – Wrap prose if it exceeds the print width.
  • "never" – Do not wrap prose.
  • "preserve" – Wrap prose as-is. First the available in v1.9.0
Default CLI Override API Override
"preserve" `–prose-wrap <always never

HTML Whitespace Sensitivity

Specifies to be sensitive to Spaces in HTML, Vue, Angular, and Handlebars files.

For example, whether or not you leave whitespace will directly affect the rendering of the page:

html output
with spaces 1<b> 2 </b>3 1 2 3
without spaces 1<b>2</b>3 123

So you need to set whitespace-sensitive formatting.

When set to CSS, different formatting methods are used according to the label’s display properties (inline, block). For example:

<! -- <span> is an inline element, <div> is a block element -->

<! -- Format the tag in a format mode -->
<span class="dolorum atque aspernatur">Est molestiae sunt facilis qui rem.</span>
<div class="voluptatem architecto at">Architecto rerum architecto incidunt sint.</div>

<! -- after formatting -->
<span class="dolorum atque aspernatur"
  >Est molestiae sunt facilis qui rem.</span
>
<div class="voluptatem architecto at">
  Architecto rerum architecto incidunt sint.
</div>
Copy the code

You can also manually specify the display type

<! Before formatting, manually specify the block property -->
<! -- display: block -->
<span class="dolorum atque aspernatur">Est molestiae sunt facilis qui rem.</span>

<! -- after formatting -->
<! -- display: block -->
<span class="dolorum atque aspernatur">
  Est molestiae sunt facilis qui rem.
</span>
Copy the code

See Whitespace-sensitive formatting for more details

  • "css"– Follow the CSSdisplayattribute
  • "strict"– All Spaces will be considered meaningful
  • "ignore"– All Spaces will be considered meaningless
Default CLI Override API Override
"css" `–html-whitespace-sensitivity <css strict

Vue files script and style tags indentation

In vue file, whether to indent code in script and style.

  • "false"– Do not add indent, for example:
<script>
export default {
    mounted() {
        console.log("Component mounted!");
    }
};
</script>
Copy the code
  • "true"– Add indent, for example:
<script> export default { mounted() { console.log('Component mounted! ') } } </script>Copy the code
Default CLI Override API Override
false --vue-indent-script-and-style vueIndentScriptAndStyle: <bool>

End of Line

Specifies whether to add a blank line at the end of the code

end-of-line

  • "lf"— Line Feed only (\n), common on Linux and macOS as well as inside git repos
  • "crlf" – Carriage Return + Line Feed characters (\r\n), common on Windows
  • "cr" – Carriage Return character only (\r), used very rarely
  • "auto" – Maintain existing line endings (mixed values within one file are normalised by looking at what’s used after the first line)
Default CLI Override API Override
"lf" `–end-of-line <lf crlf

Embedded Language Formatting

Whether you need to format the code referenced in the file

  • "auto"– If Prettier can identify the embedded code, it formats it
  • "off"– Embedded code is not formatted
Default CLI Override API Override
"auto" --embedded-language-formatting=off embeddedLanguageFormatting: "off"

After the