在 VS Code 中保存时格式化 *.tsx 文件

Dev*_*avo 14 typescript visual-studio-code react-tsx

settings.json有可能只能格式化*.ts文件有:

"[typescript]": {
    "editor.formatOnSave": true
}
Run Code Online (Sandbox Code Playgroud)

但我无法让它为*.tsx文件工作。

Dev*_*avo 30

"[typescriptreact]": {
    "editor.formatOnSave": true
}
Run Code Online (Sandbox Code Playgroud)

另请参阅特定于语言的编辑器设置

  • 是的,我也面临同样的问题。要设置默认 linter,请打开命令选项板 Ctrl+Shift+P 并配置默认格式化程序。 (4认同)
  • 终于让它工作了,我需要先手动运行格式化,然后才能保存。有冲突的 linter 尝试对同一文件进行 lint,但没有引发任何错误。如果您安装了多个 linter,上面的代码片段还需要明确设置您希望它使用哪个 linter。 (3认同)
  • 截至 2020 年 10 月 15 日,此功能不起作用,您知道发生了什么吗? (2认同)

Saf*_*thi 20

您可以安装Prettier Code formatter 扩展并将这两个选项添加到 settings.json 文件中

{
  "typescript.format.enable": false,
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 就我而言,它已添加到 settings.json 中。要使其与 `.tsx` 一起使用,只需将 `"[typescript]"` 更改为 `"[typescriptreact]"`。 (4认同)

Com*_*02x 10

就我而言,我将两者都添加到了我的文件中settings.json,因为我注意到保存时 .ts 文件未格式化,以下是更新的设置:

"[typescript]": { // for .ts files
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
},
"[typescriptreact]": { // for .tsx files
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
},
"editor.codeActionsOnSave": { // apply ESLint
    "source.fixAll.eslint": true
},
Run Code Online (Sandbox Code Playgroud)


小智 7

使用“ESLint”等插件的替代方法:

"[typescriptreact]": {
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}
Run Code Online (Sandbox Code Playgroud)