Issue #45 (Auto-formatting Code)03/01/23
Get Smarter Every Day
Every day Refind picks 5 links from around the web that make you smarter, tailored to your interests. Refind is a must-read newsletter loved by 100,000+ curious minds.
|
|
|
VS Code can help keep your code clean automatically by means of four different default settings that don't require any kind of extension. Of course, many of you are likely using some kind of extension for formatting code (Prettier would be the most popular) but this feature is available in VS Code out-of-the-box for JavaScript, TypeScript, JSON, HTML, and CSS.
These formatting options are all disabled by default but you can find them in your settings by searching for "Format on". You'll see four options:
Here's a brief overview of the options:
- Format On Paste – Useful if you're pasting code from external sources, this will format the code instantly.
- Format On Save – This will trigger formatting only when the file is saved.
- Format On Save Mode – This allows you to specify if the entire file should be formatted, or only the modifications. If you choose one of the modification options, it requires use of source control.
- Format On Type – Lets you format each line that's typed
Any of these options will only work if a formatter is available for the language being used. As mentioned, certain languages have default formatting settings in VS Code, so you can start using those right away.
But you're not limited to what the default formatters do. You can adjust the formatting to suit your own needs. For example, if you search for "javascript.format" in your settings, you should see more than a dozen options that allow you to fine-tune how VS Code formats JavaScript. The same can be done for "typescript.format", "html.format", "css.format", and "json.format" (though the JSON formatter doesn't seem to have any fine-grained options like the others).
As mentioned, there are extensions for just about any language that will serve as your default formatter once installed. The VS Code extension Marketplace has a specific
category for formatters when searching.
And if you're skilled enough, you can even build your own formatter extension for a specific language, or for multiple languages. There's a brief discussion of the subject in
this article in the VS Code docs.