如何在VS代码中保存时保存代码格式

问题描述 投票:108回答:5

我想在Visual Studio Code中保存文件时使用内置格式化程序自动格式化TypeScript代码。

我知道以下选项,但它们都不够好:

  • 手动格式化Shift + Alt + F
  • 格式类型为"editor.formatOnType": true 按Enter键时会格式化该行。不幸的是,当您鼠标单击另一条线或按向上/向下箭头时,它会使其保持未格式化。
  • 使用现有扩展 我试过这个one,但似乎效果不好。
  • 使用美化"beautify.onSave": true 它不适用于TypeScript
  • 编写自定义扩展 如果你想要正确处理自动保存和构建,这很棘手。
visual-studio-code vscode-settings code-formatting
5个回答
176
投票

截至2016年9月(VSCode 1.6),现在正式supported

将以下内容添加到settings.json文件中:

"editor.formatOnSave": true

36
投票

To automatically format code on save:

  • 按Ctrl键打开用户首选项
  • 在打开的设置文件中输入以下代码 { "editor.formatOnSave": true }
  • 保存存档

Source


20
投票

如果您想使用Javascript源自动格式保存,请将此一个添加到Users Setting(按Cmd或Ctrl,):

"[javascript]": { "editor.formatOnSave": true }

12
投票

无需再添加命令。对于那些不熟悉Visual Studio Code并且在保存时搜索格式化代码的简单方法的人,请按照以下步骤操作。

  1. 通过在Mac中按[Cmd+,]或使用以下屏幕截图打开“设置”。

VS Code - Open Settings Command Image

  1. 在搜索框中输入“格式”,然后启用“保存时格式化”选项。

enter image description here

你完成了。谢谢。


1
投票

对于MAC用户,将此行添加到默认设置中

文件路径为:/ Users / USER_NAME / Library / Application Support / Code / User / settings.json

“tslint.autoFixOnSave”:是的

该文件的样本将是:

{
    "window.zoomLevel": 0,
    "workbench.iconTheme": "vscode-icons",
    "typescript.check.tscVersion": false,
    "vsicons.projectDetection.disableDetect": true,
    "typescript.updateImportsOnFileMove.enabled": "always",
    "eslint.autoFixOnSave": true,
    "tslint.autoFixOnSave": true
}
© www.soinside.com 2019 - 2024. All rights reserved.