有人可以解释一下VS Code中所有格式化工具的工作原理吗?

问题描述 投票:1回答:2

背景

我刚开始学习react.js,并发现很多人正在使用更漂亮和eslint来格式化他们的代码。但是在我根据在线指南设置自己的内容之后,有线的事情发生了。它可以在我保存文件时正确格式化代码,但是当我手动触发格式化功能时(Shift +选项+ 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键盘shorcut(Shift +选项+ F)没有使用与autoFixOnSave相同的配置(甚至不是相同的工具)。但我也不明白这些工具是如何工作和整合在一起的,哪一个优先于哪一个。有人可以帮忙吗?

javascript reactjs eslint prettier
2个回答
1
投票

你为什么禁用js更漂亮?

你知道Prettier可以与ESLint完美融合吗?

看看这篇文章:Prettier: Integrating with 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以验证反应。


0
投票

我不是在看VS代码的mac版本,但我认为热键应该是Shift + Option + F

编辑:我通常在vscode中禁用默认的javascript格式化程序,因为它可能与我的eslint规则冲突,这使得eslint无法正确格式化我的代码。

ESLint有它自己的Fix命令,我的设置没有热键,但我有eslint.autoFixOnSave: true

Prettier不会挂钩内部vscode format命令。它也有自己的命令设置。对于大多数可用的更漂亮的扩展,运行更漂亮格式的默认热键是CMD + Shift + P -> Format Document,但如果editor.formatOnSavetrue,则会在保存时触发。

© www.soinside.com 2019 - 2024. All rights reserved.