Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

prettier-plugin-svelte

sveltejs1.9mMIT3.3.3TypeScript support: included

Svelte plugin for prettier

prettier, svelte

readme

Prettier for Svelte components

Format your Svelte components using Prettier.

Features

  • Format your HTML, CSS, and JavaScript using prettier
  • Format Svelte syntax, e.g. each loops, if statements, await blocks, etc.
  • Format the JavaScript expressions embedded in the Svelte syntax
    • e.g. expressions inside of {}, event bindings on:click="", and more

VS Code Extension

This plugin is bundled in the Svelte for VS Code extension. If you only format through the editor, you therefore don't need to do anything in addition.

The extension lets you define options through extension-specific configuration. These settings are ignored however if there's any configuration file (.prettierrc for example) present.

Prettier Plugin

Installing the plugin as a package allows:

  • customizing the formatting behavior
  • using the command line to format
  • using a different IDE
  • using the official VS Code Prettier extension to format Svelte files

Compatibility

  • prettier-plugin-svelte@3 only works with prettier@3
  • prettier-plugin-svelte@2 only works with prettier@2

Setup

Install Prettier and the plugin as a dev dependency:

npm i --save-dev prettier-plugin-svelte prettier

Then create a .prettierrc configuration file:

// .prettierrc
{
    // ..
    "plugins": ["prettier-plugin-svelte"],
    "pluginSearchDirs": ["."], // should be removed in v3
    "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

If you want to customize some formatting behavior, see section Options.

CLI Usage

Format your code using the Prettier CLI.

npx prettier --write . # v3
npx prettier --write --plugin prettier-plugin-svelte . # v2

As part of your scripts in package.json:

// package.json
{
    // ..
    "scripts": {
        "format": "prettier --write .", // v3
        "format": "prettier --write  --plugin prettier-plugin-svelte ." // v2
    }
}

If you want to customize some formatting behavior, see section Options.

Options

Configurations are optional

Make a .prettierrc file in your project directory and add your preferred options to configure Prettier. When using Prettier through the CLI, you can also pass options through CLI flags, but a .prettierrc file is recommended.

Svelte Sort Order

Sort order for svelte:options, scripts, markup, and styles.

Format: join the keywords options, scripts, markup, styles with a - in the order you want; or none if you don't want Prettier to reorder anything.

Default CLI Override API Override
options-scripts-markup-styles --svelte-sort-order <string> svelteSortOrder: <string>

The options order option only exists since version 2. If you use version 1 of prettier-plugin-svelte, omit that option (so for example only write scripts-markup-styles).

Svelte Strict Mode

More strict HTML syntax: Quotes in attributes and no self-closing DOM elements (except void elements).

In version 2 this overruled svelteAllowShorthand, which is no longer the case.

In Svelte 5, attributes are never quoted, because this will mean "stringify this attribute value" in a future Svelte version

Example:

<!-- svelteStrictMode: true (Svelte 3 and 4) -->
<div foo="{bar}"></div>
<!-- svelteStrictMode: true (Svelte 5) -->
<div foo={bar}></div>

<!-- svelteStrictMode: false -->
<div foo={bar} />
Default CLI Override API Override
false --svelte-strict-mode <bool> svelteStrictMode: <bool>

Svelte Allow Shorthand

Option to enable/disable component attribute shorthand if attribute name and expression are same.

Example:

<!-- allowShorthand: true -->
<input type="text" {value} />

<!-- allowShorthand: false -->
<input type="text" value={value} />
Default CLI Override API Override
true --svelte-allow-shorthand <bool> svelteAllowShorthand: <bool>

Svelte Bracket New Line

Deprecated since 2.5.0. Use Prettier 2.4.0 and bracketSameLine instead.

Put the > of a multiline element on a new line. Roughly the Svelte equivalent of the jsxBracketSameLine rule. Setting this to false will have no effect for whitespace-sensitive tags (inline elements) when there's no whitespace between the > of the start tag and the inner content, or when there's no whitespace after the > of the end tag. You can read more about HTML whitespace sensitivity here. You can adjust whitespace sensitivity through this setting.

Example:

<!-- before formatting -->
<span><div>foo</div><span>bar</span></span>
<div pretend break>content</div>

<!-- after formatting, svelteBracketNewLine true -->
<span
    ><div>foo</div>
    <span>bar</span></span
>
<div
     pretend
     break
>
    content
</div>

<!-- after formatting, svelteBracketNewLine false -->
<span
    ><div>foo</div>
    <span>bar</span></span>
<div
     pretend
     break>
    content
</div>
Default CLI Override API Override
true --svelte-bracket-new-line <bool> svelteBracketNewLine: <bool>

Svelte Indent Script And Style

Whether or not to indent the code inside <script> and <style> tags in Svelte files. This saves an indentation level, but might break code folding in your editor.

Default CLI Override API Override
true --svelte-indent-script-and-style <bool> svelteIndentScriptAndStyle: <bool>

.prettierrc example

{
    "svelteSortOrder": "options-styles-scripts-markup",
    "svelteStrictMode": true,
    "svelteBracketNewLine": false,
    "svelteAllowShorthand": false,
    "svelteIndentScriptAndStyle": false
}

Usage with Tailwind Prettier Plugin

  • VS Code Extension: Use it as the default formatter for Svelte files
  • Prettier Plugin: Load the Tailwind plugin in the end - Tailwind docs
// .prettierrc
{
    // ..
    "plugins": [
        "prettier-plugin-svelte",
        "prettier-plugin-tailwindcss" // MUST come last
    ]
}

Since we are using configuration overrides to handle svelte files, you might also have to configure the prettier.documentselectors in your VS Code settings.json, to tell Prettier extension to handle svelte files, like this:

// settings.json
{
    // ..
    "prettier.documentSelectors": ["**/*.svelte"]
}

Usage in the browser

Usage in the browser is semi-supported. You can import the plugin from prettier-plugin-svelte/browser to get a version that depends on prettier/standalone and therefore doesn't use any node APIs. What isn't supported in a good way yet is using this without a build step - you still need a bundler like Vite to build everything together as one self-contained package in advance.

Migration

# package.json
- "format": "prettier --plugin-search-dir . --write ."
+ "format": "prettier --write ."
# package.json
- "prettier": "^2.8.8",
+ "prettier": "^3.1.0",
- "prettier-plugin-svelte": "^2.10.1",
+ "prettier-plugin-svelte": "^3.1.0",
# .prettierrc
- "pluginSearchDirs": ["."],
+ "plugins": ["prettier-plugin-svelte"]

Version 3 contains the following breaking changes:

  • Whether or not empty elements/components should self-close is now left to the user - in other words, if you write <div /> or <Component /> that stays as is, and so does <div></div>/<Component></Component>. If svelteStrictMode is turned on, it will still only allow <div></div> notation for elements (but it will leave your components alone)
  • svelteAllowShorthand now takes precedence over svelteStrictMode, which no longer has any effect on that behavior. Set svelteAllowShorthand to false to get back the v2 behavior
  • Some deprecated svelteSortOrder options were removed, see the the options section above for which values are valid for that options

Version 3 of this plugin only works with Prettier version 3. Prettier version 3 contains some changes to how it loads plugins which may require you to adjust your configuration file:

  • Prettier no longer searches for plugins in the directory automatically, you need to tell Prettier specifically which plugins to use. This means you need to add "plugins": ["prettier-plugin-svelte"] to your config if you haven't already. Also remove the deprecated option pluginSearchDirs.
  • Prettier loads plugins from the plugin array differently. If you have used require.resolve("prettier-plugin-svelte") in your .prettierrc.cjs to tell Prettier where to find the plugin, you may need to remove that and just write "prettier-plugin-svelte" instead

FAQ

Why is the closing or opening tag (> or <) hugging the inner tag or text?

If you are wondering why this code

<span><span>assume very long text</span></span>

becomes this

<span
      ><span>assume very long text</span
    ></span
>

it's because of whitespace sensitivity. For inline elements (span, a, etc) it makes a difference when rendered if there's a space (or newline) between them. Since we don't know if your slot inside your Svelte component is surrounded by inline elements, Svelte components are treated as such, too. You can adjust this whitespace sensitivity through this setting. You can read more about HTML whitespace sensitivity here.

Version 2 does not work in pnpm

You may need to use a .prettierrc.cjs file instead to point Prettier to the exact location of the plugin using require.resolve:

module.exports = {
    pluginSearchDirs: false,
    plugins: [require('prettier-plugin-svelte')],
    overrides: [{ files: '*.svelte', options: { parser: 'svelte' } }],
};

changelog

prettier-plugin-svelte changelog

3.3.3 (unreleased)

  • (fix) Svelte 5: ensure bind get/set is broken up correctly when too long

3.3.2

  • (fix) Svelte 5: handle type annotations on Svelte control flow blocks
  • (fix) preserve style/script tags at the end of the file when using svelteSortOrder: "none"

3.3.1

  • (feat) Svelte 5: support upcoming bind:value={get, set}

3.3.0

  • (feat) Svelte 5: support upcoming <svelte:boundary>
  • (feat) Svelte 5: support upcoming <svelte:html>
  • (feat) Svelte 5: support upcoming #each without as

3.2.8

  • (chore) provide IDE tooling a way to pass Svelte compiler path

3.2.7

  • (fix) force quote style inside style directives
  • (fix) preserve commas in array expressions
  • (fix) Svelte 5: properly determine end of snippet parameters with TS annotations

3.2.6

  • (feat) Svelte 5: never quote single-expression-attributes

3.2.5

  • (fix) Svelte 5: format TypeScript in the template

3.2.4

  • (fix) speed up regex

3.2.3

  • (fix) don't force-self-close <slot> tags

3.2.2

  • (fix) handle updated @render tag AST shape

3.2.1

  • (fix) handle updated @render tag AST shape

3.2.0

  • (feat) format JSON script tags
  • (feat) introduce separate entry point using prettier/standalone
  • (fix) don't duplicate comments of nested script/style tags
  • (fix) handle updated Snippet block AST shape

3.1.2

  • (fix) handle > tags in attributes

3.1.1

  • (fix) handle types on each/await contexts

3.1.0

  • (feat) add experimental support for Svelte 5
  • (feat) support #snippet and @render

3.0.3

  • (fix) handle static tag attributes on <svelte:element>

3.0.2

  • (fix) add package.json to exports map

3.0.1

  • (fix) support less/scss in style tags

3.0.0

  • (breaking) requires prettier version 3. This may require adjustments to your configuration file, see the migration guide for more info
  • (breaking) requires node version 14 or higher
  • (breaking) Whether or not empty elements/components should self-close is now left to the user - in other words, if you write <div /> or <Component /> that stays as is, and so does <div></div>/<Component></Component>. If svelteStrictMode is turned on, it will still only allow <div></div> notation for elements (but it will leave your components alone)
  • (breaking) svelteAllowShorthand now takes precedence over svelteStrictMode, which no longer has any effect on that behavior. Set svelteAllowShorthand to false to get back the v2 behavior
  • (breaking) remove deprecated svelteSortOrder options

2.10.1

  • (chore) mark as compatible with Svelte 4

2.10.0

  • (feat) support requirePragma and insertPragma options (#350)
  • (feat) support <svelte:document>
  • (feat) trim whitespace in class attributes (#339)
  • (feat) allow multiple comments atop of script/style tags (#291)
  • (fix) handle script/style attributes without quotes (#344)

2.9.0

  • (feat) support style modifiers (#330)
  • (fix) respect strict mode and shorthand options when formatting style/class directives (#328)

2.8.1

  • (fix) format {#await .. catch ..}..{/await} correctly (#323)
  • (fix) respect strict mode and shorthand options when formatting bindings (#321)

2.8.0

  • (feat) support singleAttributePerLine Prettier option (#305)
  • (feat) add svelteSortOrder: none Prettier option which skips reordering scripts/styles/html (#305)

2.7.1

  • (fix) check for snipped content in JS expressions (#290)
  • (fix) handle <!DOCTYPE> (#298)

2.7.0

  • (feat) Support <svelte:element> (#285)
  • (fix) Respect htmlWhitespaceSensitivity: 'ignore' setting in components (#281)

2.6.0

  • (feat) Support {@const} tag (#272)
  • (feat) Support style: directive (requires Svelte 3.46.1 or later) (#274)

2.5.1

  • (fix) Better handling of destructured values with defaults in {#each} and {#await} blocks (#269)
  • (fix) Prevent <script>/<style> contents from being erased in certain cases (#268)
  • (fix) Format {expressions} inside <pre> tags (#266)

2.5.0

  • (feat) Support bracketSameLine option and deprecate svelteBracketNewLine (#251)
  • (fix) Prevent script/style contents from being erased in certain cases (#255)
  • (fix) Properly format nested array patterns (#259)

2.4.0

  • (feat) Add support for formatting Pug inside <template> tags, if the corresponding plugin is available (#248)
  • (fix) Adjust checks for whether we're inside another tag when snipping tags (#244, #246)

2.3.1

  • (fix) More robust check for hardline to prevent trailing empty lines in <style>/<script> tags (#222)

2.3.0

  • (fix) Adjust snip regex to not break commented-out <script>/<style> tags (#212)
  • (fix) Don't snip <style> tags that are inside <script> tags (#219, #70)
  • (fix) Better formatting of long attribute values with mustache tags in between (#221)
  • (fix) Format properly when using Prettier 2.3.0+ (#222)
  • (fix) Keep parentheses in <script> tags for which JS is assumed (#218)
  • (feat) Support range ignores at HTML top level (#225)

2.2.0

  • Add support for <svelte:fragment> (#213)

2.1.6

  • Fix incorrect removal of comment (#207)

2.1.5

  • Fix retrieval of comment belonging to <script>/<style> block (#205)

2.1.4

  • Don't print an empty line at the end of code embedded inside Markdown (further fixes) (#202)

2.1.3

  • Don't print an empty line at the end of code embedded inside Markdown (#202)

2.1.2

  • Keep whitespace around <script>/<style> tags (#197)
  • Make <script>/<style> tag snipping case-sensitive (#198)

2.1.1

  • Fix svelteBracketNewLine: true sometimes not having > on a separate line (#194)

2.1.0

  • Support Prettier's htmlWhitespaceSensitivity setting
  • When svelteBracketNewLine is set to true and only the closing tag has whitespace before it, print the closing > on a separate line

2.0.3

  • When svelteBracketNewLine is set to false, don't print the closing > in a separate line if possible (#183)

2.0.2

  • Fix formatting of <template> tags with an unsupported language inside

2.0.1

  • Fix formatting of inline element when there's a line at the start/end (#183)

2.0.0

This release comes with a rewrite of the HTML formatting. The output is now much more in line with how standard Prettier formats HTML. This is also why svelteBracketNewLine now defaults to true. Another notable default change is the sort order: svelte:options is now part of the sort order and the default changed to options-scripts-markup-styles, which is in line with how the majority of users like to order the code blocks.

The complete list of changes:

  • Rework the tag breaking logic with the goal to be more in line with how Prettier formats standard HTML. This includes respecting the user's decision to have child tags in separate lines even if they don't exceed the maximum line width (#143, #117). This is a breaking change because tags are broken up differently now than before.
  • <svelte:options> is now part of svelteSortOrder. Default sort order is now options-scripts-markup-styles. This is a breaking change. (#73)
  • svelteBracketNewLine defaults to true now to be more in line with how Prettier formats standard HTML. This is a breaking change
  • Fix formatting of fenced Svelte code blocks inside Markdown (#129)
  • Everything that is not explicitly a block element is now treated as an inline element, including components. This is a breaking change (#159)
  • Single quotes are no longer forced except inside quoted attributes/events/etc. This is a breaking change (#94)
  • If the content inside a {tag} is too long, break it up if possible (excluding {#if}/{#await}/etc. blocks). This is a breaking change (#170)
  • If the content of a <script>/<style> tag is completely empty (no whitespace), don't put the closing tag on a new line (#87)

1.4.2

  • Pass options to embedded parser (#162)
  • Fall back to raw text if there is a parser error in a JS expression inside a moustache tag (#163)

1.4.1

  • Format next node correctly when previous node has a comment as last child (#152)
  • Only prettier-ignore comments should ignore formatting of next line (#151)
  • Do not encode entities in attribute values (#29)
  • Fix raw printing of unsupported languages (#156)

1.4.0

  • Fix print order of attributes and body (#146)
  • Support the new {#key} block introduced in Svelte 3.28.0 (#147)

1.3.0

  • Add vscodeLanguageIds for VS Code consumers, including coc-prettier (#138)
  • Keep comments directly before <style>, <script> or <template> tags together with the tag when reformatting (#137)
  • Keep inline elements together even when inside text (#139)
  • Don't format class attributes (#145)

1.2.1

  • Skip formatting <style> or <script> tags if in an unsupported language or if prettier-ignored (#55, #59, #95)
  • Make error location properties compatible with both Svelte and Prettier (#71)
  • Handle/preserve comments in event handlers (#96)
  • Fix Node 10 compatibility (#135)

1.2.0

  • Don't format contents of <pre> or its attributes, apart from class (#28)
  • Fix whitespace issues (#58, #103, #24)
  • Add option to disable first level of indentation in <script> and <style> tags (#105)
  • Fix output when rewriting shorthand attributes to not use the shorthand syntax (#110)
  • Add support for object destructuring reassignment (#113)

1.1.1

  • Fix bug that breaks plugin when using Prettier v2.1.x (#123)
  • Fix incorrectly escaped regexp which broke style tags followed by "s" (#118)
  • Write to console.error to prevent crash and erasion of files (#115)

1.1.0

  • Support <!-- prettier-ignore --> comments (#59)
  • Fix {#await} printing with {:catch} but no pending block (#76)
  • Fix {#await} printing with only a pending block (#77)
  • Support {#await} destructuring (#83)
  • Fix other {#await} handling in Svelte versions since 3.20 (#83)

1.0.0

  • Support Prettier 2
  • Add svelteAllowShorthand option
  • This plugin has now become an official Svelte project

0.7.0

  • Add svelteStrictMode option
  • Support {#await} block shorthand syntax

0.6.0

  • Support nested <script> and <style> tags
  • Add svelteSortOrder option
  • Fix printing of HTML entities
  • Add option to add newline to closing angle bracket
  • Support all <svelte:*> elements
  • Throw Svelte parsing errors in format Prettier expects
  • Add handling for |local transition modifier
  • Prevent {#if} blocks nested in an {#each}/{:else} from being converted into an {:else if}
  • Fix whitespace trimming for lonely wrapped mustache tags

0.5.1

  • Fix attribute wrapping

0.5.0

  • Remove .html from list of extensions
  • Use typescript as parser to handle both JS and TS
  • Add support for event modifiers
  • Support Unicode content in <script> and <style> blocks
  • Don't print children for empty elements
  • Improve handling of text nodes
  • Prevent extra whitespace for <script>-only templates
  • Correctly collapse empty elements
  • Improve directive support

0.4.2

  • Fix script + css and script + module printing

0.4.1

  • Print HTML last

0.4.0

  • Drop support for v2 and fully support v3
  • Make Prettier and Svelte peer deps