Detailed explanation of Prettier code formatting tool

Table of contents

What is Prettier?

Install Prettier

Configure Prettier

Use Prettier

Instructions for using Prettier with EditorConfig

Compared with ESLint


What is Prettier?

To borrow the official words, Prettier is a stubborn code formatter that removes all original styles * and ensures that all outputted code conforms to a consistent style.

Therefore, Prettier is a code formatting tool that can maintain a consistent style for each line of code in multi-person collaborative development. Prettier is a code style guide. Prettier provides a lot of configuration items and APIs, you can choose Configure the code style you want, and use Prettier for unified formatting.

Prettier supports:

Install Prettier

instruction:

npm install --save-dev --save-exact prettier

yarn add --dev --exact prettier

Configure Prettier

Create a configuration file, command:

echo {}> .prettierrc.js

Running the command will generate a .prettierrc.js file. If your editor is vscode, it will automatically read the configuration in the .prettierrc.js file and use this configuration to format your code. The specific configuration rules are as follows:

module.exports = {
    // 每行最多字符数,默认80
    printWidth: 130,
    // 用制表符(tab)不是空格缩进行
    // 如果为true,则取编辑器tabSize值
    // 安装editorconfig编辑器插件并配置文件,则取 editorConfig 文件中设置的值
    // 具体取indent_size或者tab_width,依据indent_style值来决定
    // 如果为false,则取值为tabWidth值,但是有问题,经常需要重启编辑器才生效
    useTabs: false,
    // 指定每个缩进级别的空格数
    tabWidth: 4,
    // 在每条语句的末尾添加一个分号 默认true
    semi: false,
    // 使用单引号代替双引号 默认false
    singleQuote: true,
    // 引用对象中的属性,对象key添加引号方式  as-needed仅在需要时在对象属性周围添加引号
    quoteProps: 'as-needed',
    // 有效的尾随逗号 es5 中有效的尾随逗号(默认) | none 没有逗号 | all 尾随逗号
    trailingComma: 'none',
    // 在对象文字中的括号之间打印空格
    bracketSpacing: true,
    // 决定html元素首元素右侧尖括号(>)是否换行,不包含自闭合元素 false另起一行
    bracketSameLine: false,
    // 箭头函数参数周围包含括号 always有括号(默认) avoid无括号
    arrowParens: 'always',

    // 规定使用哪一种解析器
    // Prettier 会自动从输入文件路径推断解析器,因此您不必更改此设置
    // parser: require("./my-parser")

    // 是否缩进Vue文件中的<script>和<style>标签,
    // 不缩进可以保存缩进级别,但可能破坏编辑器中的代码折叠(默认false)
    vueIndentScriptAndStyle: true,
    // 行尾形式 lf|crlf|cr|auto  默认lf
    endOfLine: 'auto',
}

 Commonly used configurations are shown above. For more detailed configurations and usage methods, see Prettier official documentation

Similarly, you can also define a collection of files that do not need to be formatted , create a .prettierignore file, and configure files that you do not need to format. The specific configuration rules are the same as the .gitignore file, because .prettierignore is based on .gitignore and .eslintignore, such as:

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*

At this point, Prettier is configured. For more detailed configuration, please refer to the official documentation.

If you also use ESLint, install eslint-config-prettier to make ESLint and Prettier work together. It turns off any ESLint rules that are unnecessary or might conflict with Prettier.

Use Prettier

Instruction mode :

// 格式化所有文件
npx prettier --write .

// 格式化app目录下的所有文件
prettier --write app/

Automatically run with the editor: 

In vscode, first you should install the Prettier plugin , Prettier - Code formatter plugin.

Second, the editor's default formatter should be defined as follows:

// 为了确保这个扩展被其他你可能已经安装的扩展使用,确保将它设置为你的VS Code设置中的默认格式化器
// 此设置可以针对所有语言或者特定语言进行设置

// 设置编辑器默认格式化器
// 注:设置编辑器默认格式化使用prettier后不影响eslint的正常使用
"editor.defaultFormatter": "esbenp.prettier-vscode",

// 设定特定语言
"[vue]": {
	"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
}

If you want to disable Prettier on a specific language, you can either create a .prettierignorefile or use VS Code's editor.defaultFormattersettings. 

// 对除 Javascript 之外的所有语言使用 Prettier
{
   "editor.defaultFormatter": "esbenp.prettier-vscode",
   "[javascript]": {
     "editor.defaultFormatter": "<another formatter>" 
  } 
}
// 仅将 Prettier 用于 Javascript
{
   "editor.defaultFormatter": "<another formatter>",
   "[javascript]": {
     "editor.defaultFormatter": "esbenp.prettier-vscode",
     // 配置javascript(某一个特定语言的配置) 保存自动格式化     --示例配置
     // "editor.formatOnSave": false,
  } 
}

Configure the editor to format the file on save :

// prettier与ESLint不同的一点就在于prettier需要启用编辑器保存自动格式化功能才可用
"editor.formatOnSave": true,

Then you can use Prettier to format your code normally.

For more editor usage configuration and code format configuration, please refer to the official documentation .

Instructions for using Prettier with EditorConfig

If you don't know what editorConfig is, or how to use it, please see the detailed explanation of EditorConfig usage .

editorconfig and prettier are actually complementary and not contradictory, and work together to format the code.

The indent_style in editorConfig controls whether the editor uses tabs (tab) for indentation or spaces (space) for indentation, and controls the indentation style of the editor.

The useTabs in prettier controls whether to use tabs for indentation instead of spaces.

If tabs are used for indentation, that is, the value of useTabs is true, and if the editorconfig file is configured and the editorconfig plug-in is installed, the editor indentation distance takes the value configured in the editorconfig file. If indent_style = space, take the value of indent_size first, if not, take the value of tab_width; if indent_style = tab, take the value of tab_width first, if not, take the value of indent_size. If the value of useTabs is false, it takes the value of tabWidth in the prettier file.

If the editorconfig plug-in is not installed, useTabs is true, and the value is the editor tabSize value; if useTabs is false, the value is the tab_width value.

Description of priorities:

editorConfig takes precedence over the value set by the editor, provided that the editor has the EditorConfig plugin installed.

The priority of useTabs in prettier is higher than indent_style in editorConfig.

Compared with ESLint

 How does prettier  compare to ESLint/TSLint/stylelint etc?

Linters have two types of rules:

  • formatting rules

For example: max-len, no-mixed-spaces-and-tabs, keyword-spacing, comma-style, etc.

Prettier alleviates the need for this whole class of rules! Prettier will reprint the entire program from scratch in a consistent manner, so it is impossible for the programmer to make mistakes there anymore

  • Code Quality Rules

例如:no-unused-vars , no-extra-bind , no-implicit-globals , prefer-promise-reject-errors等。

Prettier doesn't have any help with these rules. They're also the most important tool a linter offers, since they're likely to catch real bugs in your code!

So, you can use Prettier for formatting and a linter for catching errors.

recommended article:

Use Prettier to uniformly format project code

Guess you like

Origin blog.csdn.net/lwx931449660/article/details/120437107