Skip to content
FLAVIO COPES
flaviocopes.com

VS Code: use language-specific settings

By

Learn how to set language-specific settings in VS Code, like a different tab size for HTML, CSS, JavaScript, and Go, using per-language settings blocks.

~~~

To use language-specific settings in VS Code, add a block like "[javascript]": { ... } to your settings.json file. Everything inside that block only applies to files of that language.

With VS Code you have the ability to customize your spaces vs tabs preference, like in any editor, and also the option to choose how many spaces should a tab take.

Different languages however might require different settings.

For example I like to have 4 spaces in HTML, but only 2 in CSS and JavaScript.

Go on the other hand wants 8 spaces (well, tabs, since gofmt formats with tabs).

How to deal with this?

You can add language-specific settings into the VS Code preferences file. Open the Command Palette (cmd+shift+p) and run Preferences: Open User Settings (JSON) to edit it directly.

This is an example that uses different settings for JS, CSS, HTML and Go files:

"[javascript]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2
},
"[css]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2
},
"[html]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 4
},
"[go]": {
    "editor.insertSpaces": false,
    "editor.tabSize": 8
}

The key is the VS Code language identifier wrapped in square brackets. You can see the identifier of the file you have open in the bottom right corner of the status bar, or by running Change Language Mode from the Command Palette.

Finding the right block automatically

You don’t have to write these blocks by hand. Run Preferences: Configure Language Specific Settings… from the Command Palette, pick the language, and VS Code creates the block for you and puts the cursor inside it.

More than indentation

Tab size is the classic use case, but any editor setting works. Two I use a lot:

"[markdown]": {
    "editor.wordWrap": "on"
},
"[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
}

This gives you word wrap only when writing prose, and Prettier on save only for JavaScript files.

If several languages share the same settings, you can combine the selectors instead of duplicating the block:

"[javascript][typescript]": {
    "editor.tabSize": 2
}

Watch out for JSX and TSX files

Here’s the catch that confused me: .jsx files are not the javascript language in VS Code. They are javascriptreact, and .tsx files are typescriptreact.

So if your "[javascript]" settings don’t seem to apply to a React component, that’s why. Fix it by extending the selector:

"[javascript][javascriptreact]": {
    "editor.tabSize": 2
}

The same trick works for any language whose files show a different identifier than you expected.

Tagged: DevTools · All topics
~~~

Related posts about devtool: