Let's talk about how ESLint and Prettier perform automatic code formatting in vscode

青灯夜游
Release: 2022-11-04 20:25:41
forward
2690 people have browsed it

Let's talk about how ESLint and Prettier perform automatic code formatting in vscode

The front-end code formatting community provides two commonly used toolsESLintandPrettier. 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 mistakeare similar principles. [Recommended learning:vscode tutorial,Programming video]

ESLint introduction

The role of ESLint## The specific usage and principles of

#ESLintare 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 ofrules, 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 as

    Using undeclared variables,Declaring but unused variables,Modifying const variables,using debuggerin the code, etc. Wait

  • Code formatting

    can be used to unify the team’s code style, such as

    with or without semicolons,Usetabor spaces,Use single quotes for strings, etc.

How to enable it in vscode ESLint

vscode Conditions for using

ESLintfor code checking:

  • First,needs to be installed in vscodeESLintplug-in and enable it, and you need to enable eslint check in thevscodeconfiguration.

    Specifically enable the following settings in the user-level setting or project-level

    settings.json:

    { "eslint.enable": true, // 开启eslint检查 }
    Copy after login

  • Secondly, you need to installeslintin the current project root directory or globally, and the dependencies in the eslint rule configuration items also need to be installed.

    If it is not installed, the following error will be output in vsconde's eslint console:

Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

  • Finally, you need to have the configuration file.eslintrc.jsor.eslintrc.jsonin the root directory of the project, orpackage.jsonin the root project Configure the rules of eslint in the configuration itemeslintConfig.

    If there is no configuration file, the eslint console will output the following error:

Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

The above three steps are indispensable. After everything is configured, we can see the result of the code being checked by eslint in the

vscodeeditor. The js code result is similar to the following picture:

Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

eslint checks two issues based on the rules for setting values: a red wavy line indicates that the variable is defined but not used; a yellow wavy line indicates that the string must use single quotes. For these errors, the vscode editor will

only display the eslint check resultsto 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'scodeActionsOnSave.source.fixAll. The details are as follows:

{ "eslint.enable": true, // 开启eslint检查 "editor.codeActionsOnSave": { // 使用eslint来fix,包括格式化会自动fix和代码质量检查会给出错误提示 "source.fixAll.eslint": true } }
Copy after login

After modification, save the code again, and some codes that do not comply with the rules will be automatically formatted. , as shown in the figure below:

Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

By the way, a reminder:

If you set

codeActionsOnSave.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" }
Copy after login

或者为指定语音设置默认格式化器:

{ "[javascript]" { "editor.defaultFormatter": "esbenp.prettier-vscode" } }
Copy after login

上面虽然在vscode启用了Prettier,但是并没有在保存文件时进行代码格式化,要想实现自动保存代码进行代码格式化,需要:

  • vscode开启代码保存时进行格式化
  • Prettier作为默认的格式化工具,或者将Prettier设置为指定语言的格式化器
  • 是否设置需要Prettier的配置文件(.prettierrc.editorconfig),有两种情况:
    • 若配置"prettier.requireConfig": true则要求根目录下有Prettier的配置文件,它会覆盖Prettier扩展中的默认配置,如下图所示;否则保存时不会自动格式化。可以参考这里

    Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

    • 若配置"prettier.requireConfig": false则不要求根目录下有配置文件,若有的话也会被感知到并以配置文件的内容为准,如下图是没有配置文件时的提示信息:

    Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

上面三个步骤的在vscode中的配置体现如下:

{ "editor.formatOnSave": true, // 开启保存文件自动格式化代码 "editor.defaultFormatter": "esbenp.prettier-vscode", // 默认的代码格式化工具 "prettier.requireConfig": true // 需要Prettier的配置文件 }
Copy after login

再啰嗦一句:若设置需要配置文件,则必须要求根目录下有配置文件.prettierrc.editorconfig中的一个或者两个同时存在,否则代码保存不会进行格式化。

可能你会对上面.editorconfig文件作为Prettier的配置文件感到疑惑,vscode的Prettier插件中有关配置文件有这样的一段描述,如下图:

Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

可以看出Prettier插件获取配置文件有一个优先级:.prettierrc>.editorconfig>vscode默认配置

上面的前两者并不是说.prettierrc.editorconfig同时存在时,后者的配置内容就被忽略,实际的表现:

.prettierrc.editorconfig同时存在时,二者内容会进行合并,若配置项有冲突,这.prettierrc的优先级更高。

ESLint与Prettier的冲突

冲突的原因

ESLintPrettier都可以进行代码格式化方面,若二者同时出现下面的情况就会出现冲突:

  • 重叠的格式化规则不一致,二者重叠的配置规则可以参考这里
  • 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

满足上面的条件就会出现冲突,借鉴这篇文章的一幅图来展示:

Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

例如当前的项目中ESLint使用array-bracket-newline配置数组项不需要换行,而Prettier对其默认是按换行进行格式化,那么该规则就出现冲突,在文件保存时代其表现下图:

Lets talk about how ESLint and Prettier perform automatic code formatting in vscode

可以看出文件保存后代码格式化时会出现闪缩的效果,这是因为二者都对代码进行了格式化,但是最终结果取决是谁最后一个进行格式化,从上图结果来看是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 } }
Copy after login

那么要搞清楚二者重叠的规则有哪些?重叠的规则有哪些是冲突的呢?好在社区有了答案可以参考这里,针对这种情况也给出了比较好的解决方案,具体来说:

在使用ESLint作为代码的格式化工具时,关闭可能与Prettier有冲突的格式化规则,把Prettier当做一个linter规则。

主要是使用下面两个包:

  • eslint-config-prettier会关闭ESLint中有关代码格式化的配置,具体参考这里

  • eslint-plugin-prettierPrettier配置成ESLint的一个插件,让其当做一个linter规则来运行,可参考其官网

注意:eslint-plugin-prettier需要项目安装Prettier依赖

这样,只需在项目根目录下的.eslintrc.js中配置如下:

{ "extends": ["plugin:prettier/recommended"] }
Copy after login

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" // 关闭规则 } }
Copy after login

这样配置后,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 } }
Copy after login

这样,在js、ts或者jsx的文件保存时,不会调用Prettier进行格式化,而是交由ESLint来完成,除此之前的语言则是使用Prettier来进行代码格式化。

补充:editor.formatOnSave vs editor.codeActionsOnSave

ESLintPrettier存在冲突的一个原因,也在于vscode对文件保存时的配置操作有重合的地方,体现在formatOnSavecodeActionsOnSave上,二者都可以实现文件保存时格式代码,有重合的地方,对称有人在vscode社区提出是否可以删除一个:"source.fixAll""">Merge/remove "editor.formatOnSave" and "editor.codeActionsOnSave->"source.fixAll""

vscode并没有采纳删除或者合并的建议,其提供这两个的配置,其出发点是不一样的,下面是社区的一段描述:

But the main difference betweencodeActionsOnSaveandformatOnSaveremains 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 followingeditor.codeActionsOnSavewill always runOrganize Importsfollowed byFix Allonce organize imports finishes:

"editor.codeActionsOnSave": [ "source.organizeImports", "source.fixAll" ]
Copy after login

更多关于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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!