Talking about Prettier

Record the learning and use of Prettier here.

What is Prettier?

Prettier is a tool for formatting code, otherwise known as a package or plugin. Its role is to " format the code " to make the code neater and easier to read. Prettier offers a variety of ways to use it, including:

  • command line tool
  • Use its API in Nodejs
  • use in browser

The most common is to use it as a command line tool. For example, there is a code file xx.jswith the following contents:

const a = {name:'张三',age: 18,
}
const b=a.age+7;
复制代码

Then you can format its contents via the command line:

npx prettier index.js
## 输出如下
# const a = { name: '张三', age: 18 };
# const b = a.age + 7;
复制代码

prettier --write index.jsSource files can be formatted directly through .

Features of Prettier

As a tool for formatting code, Prettier has its own formatting rules .

Regarding the formatting style of the code, each team and each developer has their own preferences, so the debate about the code style never stops. The father said that the public was reasonable, and the mother said that the mother was reasonable. Who should I listen to? Prettier is to end these debates: since everyone chooses to use Prettier, they will accept Prettier's formatting style by default, and if they don't accept it, don't use it .

Even so, Prettier still provides some configurable items, because everyone has too strong requirements for these configurations, such as:

  • Use single and double quotes
  • Do you need to add a semicolon at the end of the statement?
  • Indent using tab or whitespace
  • Whether the indent is 2 or 4

In actual use, we can change these options through the configuration file. Fortunately, there are not many configurations provided by Prettier, and we do not plan to add new configuration items in the future. So it's also a formatting tool with obvious self-rules .

Difference between Prettier and ESLint

Lint 工具中最著名的就是 ESLint 了,其包含的规则分为两部分:

  • 代码格式的规则,例如:
    • 每行代码的最大长度
    • 关键词之间的空格
  • 代码质量的规则,例如:
    • 变量必须先声明后使用

对于代码格式的规则,完全可以使用 Prettier 来代替。而代码质量的规则,Prettier 则无能为力。因此必须借助 ESLint 来做这部分工作。因此,Prettier 专注于格式化代码,而 ESLint 专注于提高代码质量,减少潜在的 bug

Prettier 的使用

前文说过了 Prettier 的几种使用方式。在前端项目中,一般是在命令行中使用 Prettier 。

安装 Prettier

在项目中运行如下命令:

npm install -D prettier 
复制代码

添加配置文件

项目根目录下新建两个文件:

  • .prettierignore: 无需使用 Prettier 进行代码格式化的文件或者目录名,一般可以保持和 .gitignore 的内容相同
  • prettier.config.js: Prettier 的配置文件,常见配置如下:
     module.exports = {
         // 是否加分号
        semi: true,
        // 是否用单引号
        singleQuote: true,
        // tab健的空格数
         tabWidth: 4,
        // 是否使用tab格式化
         useTabs: false,
     }
    复制代码

package.json 中增加格式化脚本

通过在 package.jsonscripts 增加脚本,就可以通过命令行格式化我们的代码文件。这里仅格式化 /src 文件下的文件:

{
  "scripts": {
    "format-all": "prettier --write src/"
  }
}
复制代码

项目根目录下运行 npm run format-all,即可发现 src 目录下的文件都被重新格式化了。

增加 VSCode 插件和配置

实际使用时,我们如果每次写完代码都去运行格式化命令把代码格式化一遍,那就太麻烦了。所以配合编辑器使用,在保存时自动格式化的功能非常重要。

安装插件

首先在 VSCode 插件中安装如下插件:esbenp.prettier-vscode

添加配置

为了保证运行项目的每个开发者能使用相同的配置,需要给 VSCode 指定 workspace 级别的配置,并将其提交到 git 中。 在项目根目录创建文件 .vscode/settings.json 并添加如下内容:

{
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
    "[vue]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
}
复制代码

这里我们使用 esbenp.prettier-vscode 插件作为代码的格式化工具,并指定在保存文件时自动格式化代码。

运行完上述步骤,在 VSCode 中编写代码就已经可以使用 Prettier 自动格式化代码了。

不过前端项目一般都会使用 ESLint 做代码检查,因此要配合 ESLint 使用还需要额外的配置。

配合 ESLint 使用

前文说过,ESLint 的规则集中也包括一些代码格式的规则,因此如果在 VSCode 中配置了使用 ESLint 做自动修复,这和 Prettier 就会产生冲突。因此需要使用 eslint-config-prettier 配置,把和 Prettier 冲突的格式化规则禁用掉。

安装 eslint-config-prettier

项目下运行:

npm install -D eslint-config-prettier
复制代码

修改 ESLint 配置

在 ESLint 配置中增加如下配置:

{
   "extends": [
         "other config",
+       "prettier"
    ]
}
复制代码

eslint-config-prettier 这个配置就是把所有跟代码格式相关的规则禁用掉,所以一定要保证 "prettier"extends 中的最后位置。这样,在编辑器中ESLint 就不会报关于格式的问题了。

eslint-config-prettier 不仅会禁用 ESLint 默认规则中的格式规则,也会禁用诸如 eslint-plugin-vueeslint-plugin-react 等插件的所有关于格式的规则,因此只需要在 extends 中增加 "prettier" 即可。 在 [email protected] 之前的版本,可能需要添加 "prettier/vue", "prettier/react" 等配置,在 8.0.0 之后,所有的规则都集中到了一起,所以无需再指定上述配置。

至此,Prettier 就可以在项目中完美运行了!

关于 eslint-plugin-prettier

查阅网络上关于 Prettier 的配置,很多会推荐使用 eslint-plugin-prettier 插件来配合 ESLint 使用。

前文说过,eslint-config-prettier 这个配置会禁用所有关于代码格式的规则,这样一来,代码中的任何格式错误都不会作为 ESLint 错误显示出来。而 eslint-plugin-prettier 这个插件是把 Prettier 的格式化规则加入到 ESLint 规则中,所以使用该插件后格式问题会以 ESLint 错误的方式显示出来。

使用 eslint-plugin-prettier 的缺点就是比只使用 Prettier 慢。

通过 Git hooks 格式化代码

如果有些团队成员并没有配置好代码自动格式化的流程,那么未经格式化的代码就会提交到仓库中,因此我们可以通过 git hooks ,在提交时对要提交的代码进行格式化。

安装 huskylint-staged

安装依赖

npm install --save-dev husky lint-staged
npx husky install
复制代码

配置 husky

package.json 增加 prepare 脚本:

{
  "scripts": {
+    "prepare": "husky install"
  }
}
复制代码

然后添加 pre-commit 钩子处理器:

npx husky add .husky/pre-commit "npx lint-staged"
复制代码

这样在使用 git commit 的时候,就会执行 lint-staged 命令。

配置 lint-staged

lint-staged 这个库可以针对处于 staged 状态的文件执行一些命令。我们在 package.json 中增加以下内容:

{
+    "lint-staged": {
+        "**/*": "prettier --write --ignore-unknown"
+    }
}
复制代码

这样在执行 npx lint-staged 命令时,lint-staged 就会执行我们设置的 prettier --write --ignore-unknown 命令,对代码进行格式化。

总结

  1. Prettier 是一个格式化代码的工具,使用它我们就不用花费更多精力去选择什么样的代码风格,只需要按照 Prettier 的规则来就好。
  2. 只要代码整齐、整洁、可读性好就够了,没有必要纠结于使用何种代码风格。
  3. 使用 eslint-config-prettier 时配置非常简单,同时比 eslint-plugin-prettier 性能更好。

本文到此结束,欢迎提出问题~

Guess you like

Origin juejin.im/post/7079725774017658911