prettier-plugin-svelte

repository·main·Indexed 21 days ago

https://github.com/sveltejs/prettier-plugin-svelte

A Prettier plugin designed to format Svelte components, including HTML, CSS, JavaScript, and Svelte-specific syntax like control flow blocks and embedded expressions. It provides configuration options for block sort order (svelteSortOrder), attribute shorthand (svelteAllowShorthand), and indentation for script and style tags (svelteIndentScriptAndStyle). Version 4.1.1 requires Prettier 3 and Svelte 5+.

Tokens
3.7K
Snippets
12
Records
16
Agent score
72%

What's inside prettier-plugin-svelte

  1. Configure prettier-plugin-svelte via .prettierrc

    main

    Create a .prettierrc file in your project root. You must register the plugin and add an override to ensure Svelte files use the svelte parser.

    // .prettierrc
    {
        "plugins": ["prettier-plugin-svelte"],
        "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }],
    }
    // .prettierrc
    {
        // ..
        "plugins": ["prettier-plugin-svelte"],
        "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }],
    }
  2. Use prettier-plugin-svelte with Tailwind CSS plugin

    main

    When using both plugins, prettier-plugin-tailwindcss must be loaded last in the plugins array.

    // .prettierrc
    {
        "plugins": [
            "prettier-plugin-svelte",
            "prettier-plugin-tailwindcss", // MUST come last
        ],
    }

    If using the VS Code Prettier extension, you may also need to update your settings.json to ensure Svelte files are recognized:

    // settings.json
    {
        "prettier.documentSelectors": ["**/*.svelte"],
    }
    // .prettierrc
    {
        // ..
        "plugins": [
            "prettier-plugin-svelte",
            "prettier-plugin-tailwindcss", // MUST come last,
        ],
    }
  3. Install prettier-plugin-svelte

    main

    To use the plugin as a package (enabling customization, CLI usage, and IDE support), install both prettier and prettier-plugin-svelte as dev dependencies.

    Compatibility Note:

    • prettier-plugin-svelte@4 requires prettier@3 and Svelte 5+.
    • prettier-plugin-svelte@3 requires prettier@3 (for Svelte 4).
    • prettier-plugin-svelte@2 requires prettier@2.
    npm i --save-dev prettier-plugin-svelte prettier
  4. Configure Svelte Allow Shorthand

    main

    Enables or disables component attribute shorthand (e.g., {value} instead of value={value}) when the attribute name and expression are identical.

    OptionDefaultCLI OverrideAPI Override
    svelteAllowShorthandtrue--svelte-allow-shorthand <bool>svelteAllowShorthand: <bool>
    <!-- allowShorthand: true -->
    <input type="text" {value} />
    
    <!-- allowShorthand: false -->
    <input type="text" value={value} />
  5. Configure Svelte Sort Order

    main

    Controls the order of svelte:options, <script>, markup, and <style> tags within a .svelte file.

    Format: Join the keywords options, scripts, markup, and styles with a -. Use none to disable reordering.

    OptionDefaultCLI OverrideAPI Override
    svelteSortOrderoptions-scripts-markup-styles--svelte-sort-order <string>svelteSortOrder: <string>
  6. Customize Svelte block sort order with svelteSortOrder

    main

    The svelteSortOrder option determines the order of <script>, <style>, and other blocks (like <svelte:options>) within a Svelte file.

    Valid parts for the sort order are:

    • scripts
    • markup
    • styles
    • options (representing <svelte:options> or similar)

    Important: All valid sort order strings (except none) must include the options part. If you provide a string that does not include options, the plugin will throw an error: svelteSortOrder is missing option 'options'.

  7. Configure Svelte Indent Script And Style

    main

    Determines whether to indent the code inside <script> and <style> tags. Enabling this saves an indentation level but may affect code folding in some editors.

    OptionDefaultCLI OverrideAPI Override
    svelteIndentScriptAndStyletrue--svelte-indent-script-and-style <bool>svelteIndentScriptAndStyle: <bool>
  8. Migrate to prettier-plugin-svelte@4

    main

    When upgrading to version 4:

    1. Svelte Version: Ensure you are using Svelte 5, as version 4 does not support older Svelte versions.
    2. Attribute Quoting: The svelteStrictMode option has been removed. Attributes are now never quoted to avoid ambiguity with future Svelte stringification behavior.
    3. Bracket Newlines: The svelteBracketNewLine option has been removed. Use Prettier's standard bracketSameLine option instead.
  9. Configure the Svelte 5 compiler path

    main

    When using the svelte parser, you can provide a custom path to a Svelte 5 compiler via the svelte5CompilerPath option. This allows you to point to a specific version or location of the compiler to be used during the parsing phase.

    If the provided path fails to load, the plugin will log a warning and fallback to the default Svelte compiler.

    // The option is used within the svelte parser's parse method:
    // options.svelte5CompilerPath
  10. Configure prettier-plugin-svelte options

    main

    The prettier-plugin-svelte plugin provides several configuration options that can be used in your .prettierrc or other Prettier configuration files. These options allow you to control the sorting of Svelte file blocks, attribute shorthand behavior, and indentation within script and style tags.

    {
      "plugins": ["prettier-plugin-svelte"],
      "svelteSortOrder": "scripts-markup-styles",
      "svelteAllowShorthand": true,
      "svelteIndentScriptAndStyle": true
    }
  11. Svelte AST printer implementation

    main

    The plugin uses a custom printer for the svelte-ast format. The printer handles:

    • print: The main printing logic for Svelte AST nodes.
    • embed: Logic for embedding sub-languages (like JS/TS inside script tags).
    • getVisitorKeys: Provides keys for traversing the AST.
    • isBlockComment: Identifies block comments.
    • printComment: Formats both Line and Block comments for output.
    export const printers: Record<string, Printer> = {
        'svelte-ast': {
            print,
            embed,
            getVisitorKeys,
            isBlockComment(comment: any) {
                return comment.type === 'Block';
            },
            printComment(commentPath: any) {
                const comment = commentPath.getValue();
                if (comment.type === 'Line') {
                    return '//' + comment.value.replace(/\r$/, '');
                }
                return '/*' + comment.value + '*/';
            },
        },
    };