Visual Studio Code Formatting Setup

Photo by chuttersnap on Unsplash

Our team has multiple software engineers working on the same codebase, formatting code sometimes becomes an issue. Depending on the editor setup, the same code working for one person might be automatically formatted by another, which results in PR often with lot of formatting changes.

The solution is to use the same formatting rules and tools across the team so the code format is standardized.

Since we mainly develop Angular application in TypeScript/HTML/Sass, below I’m going to show you my code formatting setup for those file types.

Also, the underline formatting tool VS Code uses is listed below, so if you are using other editors, you might be able to achieve the same format result.


How to format code

You can format manually or enable format on save.

  • To format manually, press SHIFT+CMD+P then type ‘format’, select ‘format document’ or ‘format selection’. Or, just press SHIFT+ALT+F
  • To enable format on save, add this line to your settings: ”editor.formatOnSave”: true

Format TypeScript

TypeScript formatting is supported by default.

Underline, VS Code is using js-beautify.

However, imports are not sorted by formatting. We can use “Typescript Hero” extension for us to automatically sort the imports.

  • To sort the imports manually, press SHIFT+CMD+P then type ‘imports’, hit ENTER on the first command.
  • To sort on save, add this to your settings: “typescriptHero.imports.organizeOnSave”: true

Format HTML

HTML formatting is supported by default.

Underline, VS Code is using js-beautify.

Please refer here for settings.

Settings:

"html.format.wrapAttributes": "force-aligned",
"html.format.enable": true,

Format Sass

VS Code has default support for SASS but we can also install ‘Sass Formatter’ extension for better support.

Underline, ‘Sass Formatter’ use ‘sass-convert’ so vim user should be able to achieve the same functionality.

Settings:

"sassFormat.indent": 2,
"sassFormat.useSingleQuotes": true,

This post belongs to a series “Know your editor: Visual Studio Code”, where it has a collection of Visual Studio Code tips and setup.