到底如何配置,才能在 vscode 中正常使用 eslint 和 prettier?

緣起

心中一直有個疑惑,添加 --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'],
    }
}

prettier-eslint

vscode 插件 prettier-eslint 的出現,提供了一個思路code

Code ➡️ prettier ➡️ eslint --fix ➡️ Formatted Code

The eslintConfig and prettierOptions can each be provided as an argument. If
the eslintConfig is not provided, then prettier-eslint will look for them
based on the fileName (if no fileName is provided then it uses
process.cwd()). Once prettier-eslint has found the eslintConfig, the
prettierOptions are inferred from the eslintConfig. If some of the
prettierOptions have already been provided, then prettier-eslint will only
infer the remaining options. This inference happens in src/utils.js.

最終以 prettierOptions 的配置優先,所以,結果可能並不符合 eslint 配置的規則。

eslint 能替代 prettier 做爲 JavaScript 格式化工具嗎?

我認爲是能夠替代的,有如下幾點理由:

  1. eslint-config-prettier 與 eslint-plugin-prettier 兩個包能夠佐證。雖然 eslint-config-prettier 是這麼介紹本身的:

    Turns off all rules that are unnecessary or might conflict with Prettier.
  2. 另外,可參考 eslint 官方文檔 Working with Custom Formatters

二者都是基於 AST 工做的,因此 eslint 是能夠替代 prettier 的。至於,格式化代碼性能上表現,因爲沒有深刻研究,不做討論。

該如何配置呢?

prettier 的優勢也是其缺點——配置簡單,而 eslint 的配置相對來講更復雜。所以,要麼單獨配置 eslint 完成格式化功能,要麼,添加 eslint-config-prettier 與 eslint-plugin-prettier 兩個包後,再配合二者一塊兒使用。

相關文章
相關標籤/搜索