Format and Lint Code on File Save

TL;DR

Add the following values to .vscode/settings.json. Create a file if it does not exist. The settings are applied to the belonging workspace only. Every time a file is saved in VS Code, the file will be formatted using the default formatter.

{
"editor.formatOnSave": true
}

Not working?

When there are multiple formatters available for a single file (extension), the ‘format on save’ feature does not work. VS Code has formatters included out of the box. Therefore, implementing Prettier can result in multiple formatters.

Prettier can be installed when initializing a SvelteKit project
When Prettier is installed, the Default Formatter is not set.

Open the command palette, select Format Document With… option, and select Configure Default Formatter…. Note that this configuration is applied to the VS Code’s User setting. (Can override with the above settings.json)

Prettier?

When there are multiple formatters for a file extension, the default formatter value is set toNone. Therefore, setting the Workspace’s default formatter to Prettier and overriding it in a per-file-extension basis is a viable option.

{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"[javascript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
},
"[typescript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
}
}

In the above example, the default formatter is esbenp.prettier-vscode and the VS Code’s included language features are used in JSON, JavaScript, and TypeScript files. (Note that VS Code language features have different names)

ESLint?

Setting editor.codeActionsOnSave.source.fixAll.eslint to true lints files on save. It basically runs ESLint: Fix all auto-fixable Problems, and can be used alongside editor.formatOnSave.

{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hyunbin

Hyunbin

Node.js and web developer using TypeScript. Undergraduate in Seoul National University.