心中一直有個疑惑,添加 --fix 參數後的 eslint 是否能替代 prettier 做爲 JavaScript 格式化工具。git
湊巧在網上看到一篇文章《到底如何配置,才能在vscode中正常使用eslint和prettier?》,聊了相似的問題。因而,順着這個思路,我也來講一說。github
eslint數組
The pluggable linting utility for JavaScript and JSX
prettierapp
Prettier is an opinionated code formatter
一個是 lint 工具,一個是格式化工具,二者本各司其職,相得益彰。但恰恰 eslint 有個附屬功能也能幹格式化的活,因而問題隨之而來——同幹一件事,規則衝突時,到底該聽誰的呢?ide
demo工具
// .prettierrc { "trailingComma": "all" } // code var a = [1, 2]
你會驚奇的發現,prettier 並無在數組最後一項以後添加逗號。其實,prettier 的這個配置等價於性能
.eslintrc.js插件
{ rules: { 'comma-dangle': [2, 'only-multiline'], } }
若是你但願老是顯示尾部的逗號,按照下面配置,那麼,衝突已發生eslint
{ rules: { 'comma-dangle': [2, 'always'], } }
vscode 插件 prettier-eslint 的出現,提供了一個思路:code
Code ➡️ prettier ➡️ eslint --fix ➡️ Formatted CodeThe
eslintConfig
andprettierOptions
can each be provided as an argument. If
theeslintConfig
is not provided, thenprettier-eslint
will look for them
based on thefileName
(if nofileName
is provided then it usesprocess.cwd()
). Onceprettier-eslint
has found theeslintConfig
, theprettierOptions
are inferred from theeslintConfig
. If some of theprettierOptions
have already been provided, thenprettier-eslint
will only
infer the remaining options. This inference happens insrc/utils.js
.
最終以 prettierOptions 的配置優先,所以,結果可能並不符合 eslint 配置的規則。
我認爲是能夠替代的,有如下幾點理由:
eslint-config-prettier 與 eslint-plugin-prettier 兩個包能夠佐證。雖然 eslint-config-prettier 是這麼介紹本身的:
Turns off all rules that are unnecessary or might conflict with Prettier.
二者都是基於 AST 工做的,因此 eslint 是能夠替代 prettier 的。至於,格式化代碼性能上表現,因爲沒有深刻研究,不做討論。
prettier 的優勢也是其缺點——配置簡單,而 eslint 的配置相對來講更復雜。所以,要麼單獨配置 eslint 完成格式化功能,要麼,添加 eslint-config-prettier 與 eslint-plugin-prettier 兩個包後,再配合二者一塊兒使用。