Svelte is an amazing front-end framework, which gives much better developer experience over other frameworks like Vue or React. To enjoy the super handy auto-format on save feature in VS Code, a little setup is needed at time of writing, here is how:
- install Svelte extension in VS Code
- in VS Code settings, add:
"editor.formatOnSave": true,
"[svelte]": {"editor.defaultFormatter": "svelte.svelte-vscode"}
The first line let VS Code triggers auto-format on save, and the second line tells VS Code to use the Svelte extension as the default formatter for svelte files. Reload VS Code, you should be able to auto-format .svelte
files on save from now on.
Note that Svelte extension internally uses prettier-plugin-svelt for auto formatting. It has no relationship with the Prettier extension in VS Code. That means, it dis-regards the Prettier extension settings in VS Code.
So what if you want to tweak the Prettier settings, such as using single quote, removing semi colon at line end … etc? You have to add a .prettierrc
file in your project root in order to configure the Prettier plugin behavoir, a sample config file as follow:
{
"semi": false,
"singleQuote": true,
"arrowParens": "avoid",
"printWidth": 120
}
Save the config and reload VS Code, custom auto-formatting on saving .svelte
files is done 🎉
P.S. some old tutorials suggest installing prettier-plugin-svelt with npm in your project. You don’t have to do it now as its already included in the Svelte extension.