簡體   English   中英

有人可以解釋一下所有格式化工具在 VS Code 中是如何工作的嗎?

[英]Can someone please explain how all the formatting tools works in VS Code?

背景

我剛開始學習 react.js,發現很多人都在使用 prettier 和 eslint 來格式化他們的代碼。 但是在我根據在線指南設置我自己的之后,有線的事情發生了。 當我保存文件時,它可以正確格式化代碼,但當我手動觸發格式功能(Shift+option+F)時則不能。 它會將文件格式化為 eslint 會給我錯誤的有線方式。

這是我正在使用的 vscode 設置:

"editor.formatOnSave": true,
"[javascript]": {
    "editor.formatOnSave": false
},
"eslint.autoFixOnSave": true,
"eslint.alwaysShowStatus": true,
"prettier.disableLanguages": [
    "js"
],
"editor.detectIndentation": true,
"editor.tabSize": 2,

我還有一個 .eslintrc 文件

{
"extends": ["react-app", "plugin:prettier/recommended"],
}

和一個 .prettierrc 文件

{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"jsxBracketSameLine": true
}

我在這里假設的是 vscode 鍵盤快捷鍵(Shift+option+F)與 autoFixOnSave 使用的配置不同(甚至不是相同的工具)。 但我也不明白這些工具是如何工作和集成在一起的,哪一個優先於哪一個。 有人可以幫忙嗎?

為什么要禁用js以獲得更漂亮的效果?

您知道 Prettier 可以與 ESLint 完美集成嗎?

看看這篇文章: Prettier:與 ESLint 集成

在您的用戶/工作區設置中,只需添加:

  "files.autoSave": "off",
  "editor.formatOnSave": true,
  "eslint.autoFixOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true,
    "source.organizeImports": true
  },
  "eslint.options": {
    "extensions": [".js", ".jsx"]
  },
  "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],

此外,建議在您的根文件夾中有一個.editorconfig

# http://editorconfig.org

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = crlf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false

最后,在您的.eslintrc文件中,添加:

"extends": ["react-app", "plugin:prettier/recommended", "prettier/react"],

查看eslint-plugin-react以驗證反應。

我不是在看 VS 代碼的 mac 版本,但我認為熱鍵應該是Shift + Option + F

編輯:我通常在 vscode 中禁用默認的 javascript 格式化程序,因為它可能與我的 eslint 規則沖突,這使得 eslint 無法正確格式化我的代碼。

ESLint 有它自己的 Fix 命令,它在我的設置中沒有熱鍵,但我有eslint.autoFixOnSave: true

Prettier 不掛鈎內部 vscode 格式命令。 它也有自己的命令設置。 對於大多數可用的漂亮擴展,運行漂亮格式的默認熱鍵是CMD + Shift + P -> Format Document但如果editor.formatOnSavetrue則會在保存時觸發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM