Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Visual studio code 如何在“保存在VS代码中”时格式化代码_Visual Studio Code_Vscode Settings_Code Formatting - Fatal编程技术网

Visual studio code 如何在“保存在VS代码中”时格式化代码

Visual studio code 如何在“保存在VS代码中”时格式化代码,visual-studio-code,vscode-settings,code-formatting,Visual Studio Code,Vscode Settings,Code Formatting,在Visual Studio代码中保存文件时,我希望使用内置格式化程序自动格式化TypeScript代码 我知道以下选项,但都不够好: 手动格式化Shift+Alt+F 类型上的格式“editor.formatOnType”:true 当您按enter键时,它会格式化该行。不幸的是,当您用鼠标单击另一行或按向上/向下箭头时,它使其未格式化 使用现有扩展 我试过这个,但似乎效果不太好 使用beautify“beautify.onSave”:true 它不适用于TypeScript 写

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

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

  • 手动格式化
    Shift+Alt+F
  • 类型上的格式
    “editor.formatOnType”:true
    • 当您按enter键时,它会格式化该行。不幸的是,当您用鼠标单击另一行或按向上/向下箭头时,它使其未格式化
  • 使用现有扩展
    • 我试过这个,但似乎效果不太好
  • 使用beautify
    “beautify.onSave”:true
    • 它不适用于TypeScript
  • 写自定义扩展名
    • 如果要正确处理自动保存和生成,这是很棘手的
截至2016年9月(VSCode 1.6),现在正式生效

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

“editor.formatOnSave”:true
要在保存时自动格式化代码:
  • 按Ctrl键打开用户首选项
  • 在打开的设置文件中输入以下代码

    {
    “editor.formatOnSave”:true
    }
    
  • 保存文件


如果您想仅使用Javascript源代码在保存时自动格式化,请将此文件添加到
用户设置中(按CmdShiftP或CtrlShiftP,然后键入
打开设置(JSON)
以打开
设置.JSON
文件)


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

文件路径为:/Users/USER\u 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
}

不再需要添加命令。对于那些不熟悉VisualStudio代码并在保存时搜索格式化代码的简单方法的人,请遵循以下步骤

  • 在Mac中按
    [Cmd+,]
    或使用下面的屏幕截图打开设置
  • 在搜索框中键入“格式”,并启用“保存时格式化”选项

  • 你完了。谢谢。

    对于eslint

    "editor.codeActionsOnSave": { "source.fixAll.eslint": true }
    

    对于任何语言的neet格式,您都可以使用
    Prettier-code formatter
    。 应用此选项后,您可以格式化代码Alt+Shift+f

    是否有排除某些文件的方法?i、 e我只想格式化.js文件,而不是.html文件。@gabodev77prettier在VS代码中有选项(例如prettier.javascriptEnable、prettier.cssEnable…),但不用于html。它能在Autosave上格式化吗?formatOnSave仅在我手动点击Cmd+S时才对我起作用。@gabrielAnzaldo查看有关如何排除某些文件/文件类型的问题:@LukeWilliams这目前不可能,这里有一个功能请求:我的版本,我开始搜索“formatOnSave”只需点击Vs代码设置UIA中的复选框,这是Vs代码自己的文档中关于此功能的注释,适用于那些尝试此答案但对什么都没有发生感到失望的人:“格式化程序必须可用,文件延迟后不得保存,编辑器不得关闭”。使此功能无法与VS代码最有用的默认行为之一Microsoft配合使用的方法。。。
    "editor.codeActionsOnSave": { "source.fixAll.eslint": true }