


Let's talk about how ESLint and Prettier perform automatic code formatting in vscode
The front-end code formatting community provides two commonly used tools ESLint
and Prettier
. They provide corresponding vscode plug-ins respectively. , the two have overlapping parts in code formatting, and conflicts will occur when the rules are inconsistent. As a front-end development editor, vscode has become more and more common. This requires developers to have a certain understanding of their use in vscode. Mastering the principles will be of great help in improving development efficiency and ensuring code quality. As the saying goes, If a worker wants to do his job well, he must first sharpen his tools
, Sharpen your knife and chop wood by mistake
are similar principles. [Recommended learning: vscode tutorial, Programming video]
ESLint introduction
The role of ESLint## The specific usage and principles of
#ESLint are beyond the scope of this article. You can check the information yourself. Everyone should know the role of
ESLint. It is a tool for checking code quality and style. By configuring a set of rules, you can check for errors in your code. Where the rules are met, some problems support automatic repair; to sum up, there are two functions:
-
Code quality check
can detect the existence of Possible errors, such asUsing undeclared variables, Declaring but unused variables, Modifying const variables, using debugger in the code, etc. Wait
-
Code formatting
can be used to unify the team’s code style, such aswith or without semicolons, Use tab
or spaces
, Use single quotes for strings, etc.
How to enable it in vscode ESLint
vscode Conditions for usingESLint for code checking:
-
First, needs to be installed in vscode ESLint
Specifically enable the following settings in the user-level setting or project-levelplug-in and enable it, and you need to enable eslint check in the
vscodeconfiguration.
settings.json
:
{ "eslint.enable": true, // 开启eslint检查 }
Copy after login Secondly, you need to install eslint
If it is not installed, the following error will be output in vsconde's eslint console:in the current project root directory or globally, and the dependencies in the eslint rule configuration items also need to be installed.
Finally, you need to have the configuration file .eslintrc.js
If there is no configuration file, the eslint console will output the following error:or
.eslintrc.jsonin the root directory of the project, or
package.jsonin the root project Configure the rules of eslint in the configuration item
eslintConfig.
vscode editor. The js code result is similar to the following picture:
only display the eslint check results to developers.
In fact,vscodeYou can use eslint to automatically repair some problematic codes when saving the file, such as the yellow wavy line in the picture above. This requires configuring eslint in vscode when saving the file. Automatically format the code, specifically set through vscode's
codeActionsOnSave.source.fixAll. The details are as follows:
{ "eslint.enable": true, // 开启eslint检查 "editor.codeActionsOnSave": { // 使用eslint来fix,包括格式化会自动fix和代码质量检查会给出错误提示 "source.fixAll.eslint": true } }
If you setcodeActionsOnSave.source.fixAll: true
, Indicates using all provided code formatting tools for code formatting, including eslint,
click here
Prettier介绍
Prettier的作用
Prettier的作用是对代码进行格式化,并不关注代码质量潜在问题的检查。
Prettier
自身的规范倾向于团队的代码风格的规范或统一,例如每行最大长度,单引号还是双引号,等号左右空格,使用tab
还是空格等等。
除了js/ts外,它还支持对多种语言进行格式化,如vue、html、css、less、scss、json、jsx等等,是一个比较综合的代码格式化工具。
有了ESLint为啥还要用Prettier
介绍ESLint
时说到它也有代码格式化的功能,为啥还需要用Prettier
,引用这篇文章介绍了几个点:
ESLint
安装和配置比较麻烦,而且 lint 的速度并不快Prettier
并不只针对 JavaScript,它可以格式化各种流行语言Prettier
的配置选项没那么眼花缭乱,比ESLint
少很多,这在Prettier选项的哲学中说明精简的原因。
如何在vscode启用Prettier
在vscode
中启用Prettier
相对来说比较简单,并不需要在当前项目中安装Prettier
,只需:
在vscode中安装
Prettier
插件并启用,同时需要设置Prettier
为对应的代码默认格式化,或者将其设置为指定语言的代码格式化。
在用户级别的settings.json
中设置编辑器的默认代码格式化器:
{ "editor.defaultFormatter": "esbenp.prettier-vscode" }
或者为指定语音设置默认格式化器:
{ "[javascript]" { "editor.defaultFormatter": "esbenp.prettier-vscode" } }
上面虽然在vscode启用了Prettier,但是并没有在保存文件时进行代码格式化,要想实现自动保存代码进行代码格式化,需要:
- vscode开启代码保存时进行格式化
- 将
Prettier
作为默认的格式化工具,或者将Prettier
设置为指定语言的格式化器 - 是否设置需要
Prettier
的配置文件(.prettierrc
或.editorconfig
),有两种情况:若配置
"prettier.requireConfig": true
则要求根目录下有Prettier的配置文件,它会覆盖Prettier
扩展中的默认配置,如下图所示;否则保存时不会自动格式化。可以参考这里。
若配置
"prettier.requireConfig": false
则不要求根目录下有配置文件,若有的话也会被感知到并以配置文件的内容为准,如下图是没有配置文件时的提示信息:
上面三个步骤的在vscode中的配置体现如下:
{ "editor.formatOnSave": true, // 开启保存文件自动格式化代码 "editor.defaultFormatter": "esbenp.prettier-vscode", // 默认的代码格式化工具 "prettier.requireConfig": true // 需要Prettier的配置文件 }
再啰嗦一句:若设置需要配置文件,则必须要求根目录下有配置文件.prettierrc
或.editorconfig
中的一个或者两个同时存在,否则代码保存不会进行格式化。
可能你会对上面.editorconfig
文件作为Prettier
的配置文件感到疑惑,vscode的Prettier
插件中有关配置文件有这样的一段描述,如下图:
可以看出Prettier
插件获取配置文件有一个优先级:.prettierrc
> .editorconfig
> vscode默认配置
。
上面的前两者并不是说.prettierrc
和.editorconfig
同时存在时,后者的配置内容就被忽略,实际的表现:
.prettierrc
和.editorconfig
同时存在时,二者内容会进行合并,若配置项有冲突,这.prettierrc
的优先级更高。
ESLint与Prettier的冲突
冲突的原因
ESLint
和Prettier
都可以进行代码格式化方面,若二者同时出现下面的情况就会出现冲突:
- 重叠的格式化规则不一致,二者重叠的配置规则可以参考这里。
- vscode同时开启二者进行格式化
{ "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "prettier.requireConfig": true, "eslint.enable": true, // eslint开启 "editor.codeActionsOnSave": { "source.fixAll.eslint": true // 代码保存使用eslint格式化 } }
Copy after login
满足上面的条件就会出现冲突,借鉴这篇文章的一幅图来展示:
例如当前的项目中ESLint
使用array-bracket-newline
配置数组项不需要换行,而Prettier
对其默认是按换行进行格式化,那么该规则就出现冲突,在文件保存时代其表现下图:
可以看出文件保存后代码格式化时会出现闪缩
的效果,这是因为二者都对代码进行了格式化,但是最终结果取决是谁最后一个进行格式化,从上图结果来看是Prettier
是最后执行,它的格式化的结果为最终输出结果,原因:
Prettier
的格式化耗时 >ESLint
的格式化耗时
最终以Prettier
的格式化结果来输出,但是这就与ESLint
的规则冲突,vscode编辑器就会将ESLint
结果给展示出来。
以和为贵:ESLint与Prettier和谐共处
鉴于Prettier
在代码格式化方面的优劣:
- 优势:可以对多种语言进行代码格式化,不仅仅是javascript
- 劣势:不具备代码质量检查的能力
所以最佳方案是整合二者,取各方之长。但上一节分析了两者同时存在时冲突的原因,那么在二者共存的情况下解决思路就比较明确了,有两种方案:
- 二者重叠的格式化规则保持一致
- 二者共同作用的语言使用其中一种进行格式化
下面分别对这两种方案进行介绍。
二者重叠的格式化规则保持一致
前面提到,二者之所以出现冲突的条件之一是同时在vscode中开启:
{ "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "prettier.requireConfig": true, "eslint.enable": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": true } }
那么要搞清楚二者重叠的规则有哪些?重叠的规则有哪些是冲突的呢?好在社区有了答案可以参考这里,针对这种情况也给出了比较好的解决方案,具体来说:
在使用
ESLint
作为代码的格式化工具时,关闭可能与Prettier
有冲突的格式化规则,把Prettier当做一个linter规则。
主要是使用下面两个包:
eslint-config-prettier
会关闭ESLint
中有关代码格式化的配置,具体参考这里。eslint-plugin-prettier
把Prettier
配置成ESLint
的一个插件,让其当做一个linter规则来运行,可参考其官网。
注意:
eslint-plugin-prettier
需要项目安装Prettier
依赖
这样,只需在项目根目录下的.eslintrc.js
中配置如下:
{ "extends": ["plugin:prettier/recommended"] }
而plugin:prettier/recommended
帮我们做了如下事情:
{ "extends": ["prettier"], // 使用eslinst-config-prettier中的配置项 "plugins": ["prettier"], // 注册该prettier插件 "rules": { "prettier/prettier": "error", // 在eslint中运行prettier,并启用该插件提供的规则 "arrow-body-style": "off", // 关闭规则 "prefer-arrow-callback": "off" // 关闭规则 } }
这样配置后,ESLint
进行格式化时就会忽略跟Prettier
重叠的格式规则,这些交由Prettier
来进行格式化,这样二者可以愉快地一起分工协作了。
二者共同作用的语言使用其中一种进行格式化
方案一让二者协同工作的思路在ESLint
中关闭跟Prettier
可能存在冲突的规则,但是并没有避免二者同时格式化,也就是说实际上二者都参与了代码的格式化,只是输出内容一致而已。
可以从vscode的用户settings.json
配置文件可以看出:
"editor.formatOnSave": true
和"editor.defaultFormatter": "esbenp.prettier-vscode"
配置,告诉vscode在文件保存时都使用默认的Prettier
来对代码格式化。
而editor.codeActionsOnSave.source.fixAll.eslint: true
设置代码保存时使用ESLint
来进行格式化。
因为方案一本质上执行了两次代码格式化,所以我们可以有另一种思考:只使用二者中的一个进行代码格式化。
我们知道,ESLint
只对javascript、typescript以及javascrpitreact进行代码格式化,而对其他语言则无效,而Prettier
是可以的,所以针对二者共同作用的语言,我们可以关闭文件保存时自动格式化,也就是关闭Prettier
作为代码格式化工具,如下配置:
{ "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", //针对共用的语言如JS、TS和JSX关闭文件保存自动格式化功能,通过eslint来做这件事 "[javascript]": { "editor.formatOnSave": false }, "[javascriptreact]": { "editor.formatOnSave": false }, "[typescript]": { "editor.formatOnSave": false }, "editor.codeActionsOnSave": { //告诉ESLint插件在保存时运行 "source.fixAll.eslint": true } }
这样,在js、ts或者jsx的文件保存时,不会调用Prettier
进行格式化,而是交由ESLint
来完成,除此之前的语言则是使用Prettier
来进行代码格式化。
补充:editor.formatOnSave vs editor.codeActionsOnSave
ESLint
和Prettier
存在冲突的一个原因,也在于vscode对文件保存时的配置操作有重合的地方,体现在formatOnSave
和codeActionsOnSave
上,二者都可以实现文件保存时格式代码,有重合的地方,对称有人在vscode社区提出是否可以删除一个:"source.fixAll""">Merge/remove "editor.formatOnSave" and "editor.codeActionsOnSave->"source.fixAll""。
vscode并没有采纳删除或者合并的建议,其提供这两个的配置,其出发点是不一样的,下面是社区的一段描述:
But the main difference between codeActionsOnSave
and formatOnSave
remains that:
- the latter (
formatOnSave
) only formats code, - while the former (
codeActionsOnSave
) can run one or several commands on the code, commands which might not be related to formatting.
The following editor.codeActionsOnSave
will always run Organize Imports
followed by Fix All
once organize imports finishes:
"editor.codeActionsOnSave": [ "source.organizeImports", "source.fixAll" ]
更多关于VSCode的相关知识,请访问:vscode基础教程!
The above is the detailed content of Let's talk about how ESLint and Prettier perform automatic code formatting in vscode. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Step 1: After opening the vscode software interface, click the settings button in the settings menu below. Step 2: Find the Git option under the Extensions column. Step 3: Click to check the enablesmartcommit button.

1. First, use vscode software to write an html program. 2. Then, click the search button and enter openinbrowser. 3. After the installation is complete, you need to restart the software, then right-click on the HTML document and select openindefaultbrowser in the drop-down menu. 4. Finally, the software will open with the default browser.

1. After opening the interface, click the mouse to select an item that needs to be deleted. 2. Find the close folder option in the file menu in the upper left corner. 3. Finally, find the specific location of the file in the document and right-click to delete it.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

1. First, after opening the Vscode interface, click the Settings option in the Git menu 2. Then, click the Advanced button in the text editor column 3. Finally, scroll down the page with the mouse and find the vertical scroll sensitivity option in the scroll sensitivity section , just modify the parameters

1. After opening the interface, click the search icon on the left. 2. Enter the keyword content you need to search in the dialog box. 3. Press the Enter key to display all matching items. 4. Select a directory to search. 5. Right-click the mouse and select the FindinFolder button 6. You can limit the search scope to this directory. After pressing Enter again to query, we can see that the items being searched have been greatly reduced.

In the world of front-end development, VSCode has become the tool of choice for countless developers with its powerful functions and rich plug-in ecosystem. In recent years, with the rapid development of artificial intelligence technology, AI code assistants on VSCode have sprung up, greatly improving developers' coding efficiency. AI code assistants on VSCode have sprung up like mushrooms after a rain, greatly improving developers' coding efficiency. It uses artificial intelligence technology to intelligently analyze code and provide precise code completion, automatic error correction, grammar checking and other functions, which greatly reduces developers' errors and tedious manual work during the coding process. Today, I will recommend 12 VSCode front-end development AI code assistants to help you in your programming journey.

First, open a Visual Studio Code interface and click the settings icon in the lower left corner. After clicking the settings icon option, a drop-down menu pops up and selects the settings option to enter the settings interface. Click the breadcrumbs option on the left to enter the breadcrumbs interface. Check the Display Type Parameters option. After checking the Display Type Parameters option, the current settings will be automatically saved.
