【问题标题】:How do you format code on save in VS Code在 VS Code 中保存时如何格式化代码
【发布时间】:2017-01-22 11:40:21
【问题描述】:

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

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

  • 手动格式化Shift + Alt + F
  • "editor.formatOnType": true 类型的格式
    • 当您按下回车时,它会格式化该行。不幸的是,当您单击另一行或按向上/向下箭头时,它会保持未格式化。
  • 使用现有扩展
    • 我试过这个one,但它似乎不太好用。
  • 使用美化"beautify.onSave": true
    • 它不适用于 TypeScript
  • 编写自定义扩展
    • 如果您想正确处理自动保存和构建,这很棘手。

【问题讨论】:

    标签: visual-studio-code vscode-settings code-formatting


    【解决方案1】:

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

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

    "editor.formatOnSave": true
    

    【讨论】:

    • 有没有办法排除某些文件?即我只想格式化 .js 文件而不是 .html 文件。
    • VS Code 中的 @gabodev77prettier 有这方面的选项(例如 prettier.javascriptEnable、prettier.cssEnable...),但不适用于 HTML。
    • 可以在自动保存中格式化吗? formatOnSave 只有在我手动点击 Cmd+S 时才对我有用。
    • @gabrielAnzaldo 请参阅此问题以了解如何排除某些文件/文件类型:stackoverflow.com/questions/44831313/…
    • @LukeWilliams 这目前是不可能的,这里有一个功能请求:github.com/microsoft/vscode/issues/45997
    【解决方案2】:

    如果您想仅使用 Javascript 源在保存时自动格式化,请将其添加到 Users Setting(按 CmdShiftP或 CtrlShiftP 然后输入 Open Settings (JSON) 以打开 settings.json 文件)

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

    【讨论】:

    • 我的版本,我开始搜索“formatOnSave”,只需单击 Vs 代码设置 UI 中的复选框
    【解决方案3】:

    对于 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
    }
    

    【讨论】:

      【解决方案4】:

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

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

      1. 在搜索框中输入“format”并启用“Format On Save”选项。

      你已经完成了。谢谢。

      【讨论】:

        【解决方案5】:

        对于 eslint:

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

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            猜你喜欢
            • 2019-08-27
            • 1970-01-01
            • 2022-10-19
            • 2018-09-21
            • 2020-08-18
            • 2021-04-06
            • 2020-02-27
            • 2019-05-03
            • 2019-03-06
            相关资源
            最近更新 更多