how to use prettier-plugin-svelte with prettier-plugin-tailwindcss

1.1k views Asked by At

I'm trying to use prettier to format svelte files with tailwind classes, so that tailwind utilities classes get automatically sorted following tailwind's recommended order

I followed this docs:

but when I try to format any svelte file I get a "Extension 'Prettier - Code Formatter' is configured as formatter but it cannot format 'Svelte' files"

enter image description here

And when I try to configure it the only available option is:

enter image description here

these are the steps I took:

pnpn create svelte@latest svelte-prettier-tailwindcss

◇ Which Svelte app template?
│ Skeleton project
│
◇ Add type checking with TypeScript?
│ Yes, using TypeScript syntax
│
◇ Select additional options (use arrow keys/space bar)
│ Add Prettier for code formatting

pnpn exec svelte-add@latest tailwindcss

pnpm install -D prettier prettier-plugin-tailwindcss

this is my .prettierrc file

{
    "useTabs": true,
    "singleQuote": true,
    "trailingComma": "none",
    "printWidth": 100,
    "plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
    "pluginSearchDirs": false,
    "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

and this is my ./vscode/settings.json file

{
    "editor.formatOnSave": true,
    "[svelte]": {
        // "editor.defaultFormatter": "svelte.svelte-vscode" // this works, but it doesn't use tailwindcss plugin!
        "editor.defaultFormatter": "esbenp.prettier-vscode" // this doesn't work
    }
}

Then I create this +page.svelte page

<h1 class="text-sm bg-fuchsia-200">Tailwind will reformat this (text-sm goes last)</h1>

<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

If I run pnpm run format the prettier tailwindcss uses the tailwind css pluing

but if I press ctrl-shift-I (or ctrl-shift-P format document) I get the error about prettier code not being able to format svelte files.

Any idea?

1

There are 1 answers

0
opensas On

I had to add "prettier.documentSelectors": ["**/*.svelte"] to my vscode settings file

The reason for this option is explained here

Since prettier-plugin-svelte is overriding svelte files from the .prietterrc file (with { files: ['*.svelte'], options: { parser: 'svelte' } }) we also need to let the prettier vscode extension know that it can handle svelte files.

this is how my settings.json ended up:

{
    "prettier.documentSelectors": ["**/*.svelte"],
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "svelte.enable-ts-plugin": true
}

and this is the .prettierrc file

{
    "useTabs": true,
    "singleQuote": true,
    "trailingComma": "none",
    "printWidth": 100,
    "plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
    "pluginSearchDirs": false,
    "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}