How do you format code on save in VS Code
Asked Answered
J

13

449

I would like to automatically format TypeScript code using the build-in formatter when I save a file in Visual Studio Code.

I'm aware of the following options, but none of them is good enough:

  • Format manually Shift + Alt + F
  • Format on type "editor.formatOnType": true
    • It formats the line when you press enter. Unfortunatelly, it leaves it unformatted when you mouse-click another line or press up/down arrow.
  • Use existing extension
    • I tried this one, but it does not seem to work too well.
  • Use beautify "beautify.onSave": true
    • It does not work with TypeScript
  • Write custom extension
    • It's tricky if you want to handle autosaves and builds correctly.
Jaques answered 14/9, 2016 at 15:26 Comment(1)
If you have the prettier extension installed. On windows press Alt + Shift + f or search @id:editor.defaultFormatter in the settings and choose prettier as the default formatter.Illumine
J
638

As of September 2016 (VSCode 1.6), this is now officially supported.

Add the following to your settings.json file:

"editor.formatOnSave": true

Here is the menu to access the settings enter image description here

Jaques answered 11/10, 2016 at 8:39 Comment(9)
is there a way to exclude some files? i.e I want to only format .js files not .html files.Haley
@gabodev77prettier in VS Code has options for this (e.g. prettier.javascriptEnable, prettier.cssEnable...) though not for HTML.Messapian
Can it format on Autosave? formatOnSave is working for me only when I manually hit Cmd+S.Messapian
@Haley See this question for how to exclude certain files / file types: #44831813Neuro
@LukeWilliams This is currently not possible, there's a feature request for it here: github.com/microsoft/vscode/issues/45997Neuro
I don't want it too format on Autosave anymore actually (2 years later)... setting up cmd+s as well as format-on-commit (with Husky and lint-staged) works perfectly and ensures that nothing unformatted gets checked in. Thanks for the info though @Gama11!Messapian
Personally I do want the format on autosave - a shame the issue got closed by a bot without a satisfactory explanation :-(Consequently
To have this only work for C#: "[csharp]": { "editor.formatOnSave": true },Superinduce
Don't forget to "Cmd+Shift+P" and "reload window" to apply the changesHeterolecithal
I
211

No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.

  1. Open Settings by pressing [Cmd+,] in Mac (or [Ctrl+,] in Windows/Linux) or using the below screenshot.

VS Code - Open Settings Command Image

  1. Type 'format' in the search box and enable the option 'Format On Save'.

enter image description here

You are done. Thank you.

Idle answered 13/2, 2019 at 7:54 Comment(0)
T
102

If you would like to auto format on save just with Javascript source, add this one into Users Setting (press CmdShiftP or CtrlShiftP then type Open Settings (JSON) to open settings.json file)

"[javascript]": { "editor.formatOnSave": true }
Trabue answered 31/5, 2018 at 5:36 Comment(2)
my version, i started searching "formatOnSave" and just had to click a checkbox in the Vs Code Settings UIArbitrament
For multiple languages, this syntax works: "[rust][javascript]": { ... }Baisden
P
28

For eslint:

"editor.codeActionsOnSave": { "source.fixAll.eslint": true }
Proverb answered 11/12, 2020 at 23:12 Comment(0)
B
20

For neet formatting for any language you can use Prettier - code formatter. After applying this you can format code Alt + Shift + f enter image description here

Biddable answered 2/5, 2021 at 7:8 Comment(0)
T
12

The best to avoid conflicts is defining individual formatters for each language, for instance if I am working with Rust and Typescript I would like to format code using the extensions Rust-Analyzer and Prettier respectively, therefore on my .vscode/settings.json:

{
  "editor.defaultFormatter": null,
  "[rust]": {
    "editor.defaultFormatter": "rust-lang.rust-analyzer",
    "editor.formatOnSave": true
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
  }
}

Remember that both Prettier and rust-analyzer extensions must be installed first.

Tollman answered 3/9, 2022 at 9:52 Comment(0)
H
10

If you use Prettier and this line

"editor.formatOnSave": true

Doesn't work to format on save, you might need to add another command to settings.json

"editor.defaultFormatter": "esbenp.prettier-vscode",

Helminthology answered 10/11, 2022 at 21:48 Comment(1)
thank you, "editor.defaultFormatter": "esbenp.prettier-vscode", helped meLoricate
E
6

For MAC user, add this line into your Default Settings

File path is: /Users/USER_NAME/Library/Application Support/Code/User/settings.json

"tslint.autoFixOnSave": true

Sample of the file would be:

{
    "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
}
Exeunt answered 27/9, 2018 at 7:39 Comment(0)
R
5

After hours of struggle... below steps worked.
Full details below.

  1. Install this extension

https://marketplace.visualstudio.com/items?itemName=pucelle.run-on-save

  1. Add below json, to below file:

File:

<your-project-directory>\.vscode\settings.json
    OR
%UserProfile%\AppData\Roaming\Code\User\settings.json

JSON:

NOTE: Make sure commas before and after below block.

    "files.autoSave": "afterDelay",
    "files.autoSaveDelay": 1000,
    "runOnSave.statusMessageTimeout": 3000,
    "runOnSave.commands": [
        {
            "match": ".*\\.*",
            "command": "editor.action.formatDocument",
            "runIn": "vscode"
        }
    ],

Now, when the code is changed, after 1 second, it gets formatted & saved automatically.

Rossiya answered 14/1, 2022 at 10:40 Comment(3)
This actually worked quite well. To make this even better you can install Prettier - Code formatter so formatting becomes cleaner instead of the default vs code formatter. I also changed the runOnSave.statusMessageTimeout to a bit more so it doesn't just interrupt your coding flow and formats it.Mallory
I meant autoSaveDelay instead of statusMessageTimeout , mbMallory
Fun with vscode, after installing the extension and adding the two runonsave entries in setting, the autosave does not work anymore. But the autoformat works. Wait, it works, I had the delay with a high value, so plus one, although you should have been more detailed regarding the two key descriptions of runonsaveCaitlyncaitrin
B
5

For me formatOnSave wasn't working because I had prettier installed and hadn't yet chosen between the built-in and prettier as my default formatter.

To trigger the selection dialog I had to press Alt + Shift + f on my json file.

Bellarmine answered 29/1, 2022 at 6:43 Comment(0)
P
1

First, you need to choose the formatter which you have just added as an extension. Press ctrl + alt + f and choose the formatter that you want from the dropdown. Post that with every save it will get automatically formatted.

Pinnatisect answered 8/8, 2022 at 8:5 Comment(0)
O
0

In addition to enabling setting Format On Save, for python developers, you may need to install autopep8 package which is used by vscode as default to format the python code when the code is saved.

pip install autopep8

and then, press ctrl + s to see changes.

Ogre answered 24/5, 2022 at 6:35 Comment(0)
T
0

Goto settings and search format
check Editor: Format On Save

or follow these steps

Update your settings

Titoism answered 15/9, 2022 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.