How do you change the formatting options in Visual Studio Code?
I know you can Format Code using Ctrl+F / Cmd+F in Visual Studio Code but how do you change the formatting options for each language?
For example, in Visual Studio 2013 I can choose compact mode for CSS.
Is there another hidden JSON file to do that?
Solution 1:
Update 2022
Solution A:
Press Ctrl+Shift+P
Then type Format Document With...
At the end of the list click on Configure Default Formatter...
Now you can choose your favorite beautifier from the list.
Solution B:
go to file -> preferences -> settings
search for format
,
on the left side, click on Text Editor
, the very first item on the right side is Editor: Default Formatter
from the dropdown you can pick any document formatter which you installed before.
Solution 2:
If we are talking Visual Studio Code nowadays you set a default formatter in your settings.json
:
// Defines a default formatter which takes precedence over all other formatter settings.
// Must be the identifier of an extension contributing a formatter.
"editor.defaultFormatter": null,
Point to the identifier of any installed extension, i.e.
"editor.defaultFormatter": "esbenp.prettier-vscode"
You can also do so format-specific:
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[sass]": {
"editor.defaultFormatter": "michelemelluso.code-beautifier"
},
Also see here.
You could also assign other keys for different formatters in your keyboard shortcuts (keybindings.json
). By default, it reads:
{
"key": "shift+alt+f",
"command": "editor.action.formatDocument",
"when": "editorHasDocumentFormattingProvider && editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly"
}
Lastly, if you decide to use the Prettier plugin and prettier.rc
, and you want for example different indentation for html, scss, json...
{
"semi": true,
"singleQuote": false,
"trailingComma": "none",
"useTabs": false,
"overrides": [
{
"files": "*.component.html",
"options": {
"parser": "angular",
"tabWidth": 4
}
},
{
"files": "*.scss",
"options": {
"parser": "scss",
"tabWidth": 2
}
},
{
"files": ["*.json", ".prettierrc"],
"options": {
"parser": "json",
"tabWidth": 4
}
}
]
}
Solution 3:
I just found this extension called beautify in the Market Place and yes, it's another config\settings file. :)
Beautify javascript, JSON, CSS, Sass, and HTML in Visual Studio Code.
VS Code uses js-beautify internally, but it lacks the ability to modify the style you wish to use. This extension enables running js-beautify in VS Code, AND honouring any .jsbeautifyrc file in the open file's path tree to load your code styling. Run with F1 Beautify (to beautify a selection) or F1 Beautify file.
For help on the settings in the .jsbeautifyrc see Settings.md
Here is the GitHub repository: https://github.com/HookyQR/VSCodeBeautify