svelte-preprocess

repository·main·Indexed 23 days ago

https://github.com/sveltejs/svelte-preprocess

A Svelte preprocessor wrapper with baked-in support for commonly used preprocessors. It allows developers to use languages other than standard JS, HTML, and CSS within Svelte components, including TypeScript, SCSS, Pug, PostCSS, Less, Stylus, CoffeeScript, and Babel. It features auto-preprocessing based on lang attributes, support for external files via src attributes, and the ability to define markup inside custom template tags.

Tokens
9.2K
Snippets
28
Records
52
Agent score
83%

What's inside svelte-preprocess

  1. Load external files via src attribute

    main

    You can load the content of your template, script, or style tags from external files using the src attribute.

    Important: You must use a relative path starting with a dot (.) for the src attribute to be recognized by svelte-preprocess.

    <template src="./template.html"></template>
    <script src="./script.js"></script>
    <style src="./style.css"></style>
  2. Configure global styles in Svelte components

    main

    There are two ways to handle global styles within a Svelte component:

    1. The global attribute: Adding global to a <style> tag prevents Svelte from scoping the CSS, making all styles within that block global.
    2. The :global rule: Use the :global selector to expose specific parts of a stylesheet to the global scope. This works best with nesting-enabled CSS preprocessors (like SCSS) and requires PostCSS to be installed.
    <style global>
      div {
        color: red;
      }
    </style>
    <style lang="scss">
      .scoped-style {
      }
    
      :global {
        @import 'global-stylesheet.scss';
    
        .global-style {
          .global-child-style {
          }
        }
      }
    </style>
  3. How auto-preprocessing works in svelte-preprocess

    main

    In auto-preprocessing mode, svelte-preprocess automatically detects and applies the correct preprocessor based on the src, lang, or type attribute of a tag (e.g., <script lang="ts">). It also handles the <template> tag for markup, external files, and global styling. This mode is the recommended way to use the library as it is less verbose and only imports underlying compilers when a component actually uses that language.

    You can use svelte-preprocess alongside other Svelte preprocessors (like mdsvex) by passing an array to the preprocess option in your Svelte plugin configuration.

    import svelte from 'rollup-plugin-svelte'
    import { sveltePreprocess } from 'svelte-preprocess'
    
    export default {
      plugins: [
        svelte({
          preprocess: sveltePreprocess({ ... })
        })
      ]
    }
  4. Use template tags for markup

    main

    You can define your component markup inside a specific tag instead of the default HTML structure. By default, svelte-preprocess looks for a <template> tag. This provides Vue-like support for defining markup.

    <template>
      <div>Hey</div>
    </template>
    
    <style></style>
    
    <script></script>
  5. Configure svelte-preprocess with multiple languages

    main

    You can pass an options object to sveltePreprocess() to configure specific processors like postcss, scss, ts, etc.

    Important: svelte-preprocess only handles content passed to it by the Svelte loader. If your component imports a non-Svelte file (e.g., a .ts file), your bundler (like Rollup) must also be configured to handle that file type using a plugin like @rollup/plugin-typescript.

    import svelte from 'rollup-plugin-svelte'
    import { sveltePreprocess } from 'svelte-preprocess';
    + import typescript from '@rollup/plugin-typescript';
    
    export default {
      plugins: [
    +    typescript({ sourceMap: !production }),
        svelte({
    +      preprocess: sveltePreprocess({
    +         sourceMap: !production,
    +         postcss: {
    +           plugins: [require('autoprefixer')()]
    +         }
    +      }),
          // ...
        }),
      ],
    }
  6. Migrate from v5 to v6: Requirements and TypeScript configuration

    main

    Upgrading to v6 introduces several environment and configuration requirements:

    Environment Requirements

    • Svelte: Version 4 or higher is required.
    • Node.js: Version 18 or higher is required.
    • TypeScript: Minimum version 5.0 is required.

    TypeScript Configuration

    You must set "verbatimModuleSyntax": true in your tsconfig.json. This replaces the deprecated preserveValueImports and importsNotUsedAsValues options.

    Note on Imports: Because the handleMixedImports transpiler was removed, you must explicitly distinguish between type and value imports using the type keyword:

    // Instead of: import { value, Type } from 'somewhere'
    import { value, type Type } from 'somewhere';
  7. Integrate svelte-preprocess with svelte-loader

    main

    To use svelte-preprocess with Webpack via svelte-loader, include it in the options.preprocess field of your loader configuration for .html or .svelte files.

    // webpack config snippet
    module: {
      rules: [
        {
          test: /\.(html|svelte)$/,
          exclude: [],
          use: {
            loader: 'svelte-loader',
            options: {
              preprocess: require('svelte-preprocess')({
                /* options */
              })
            },
          },
        },
      ]
    }
  8. Install language-specific dependencies for svelte-preprocess

    main

    Depending on which languages you want to support in your Svelte components, install the corresponding packages:

    • Babel: @babel/core, @babel/preset-...
    • CoffeeScript: coffeescript
    • TypeScript: typescript
    • PostCSS: postcss, postcss-load-config
    • SugarSS: postcss, sugarss
    • Less: less
    • Sass: sass
    • Pug: pug
    • Stylus: stylus
  9. Migrate from v3 to v4: Defining preprocessor properties

    main

    In v4, the transformers property was removed. Language options (like scss or typescript) should now be defined directly in the root object passed to sveltePreprocess().

    // v4 pattern
    import { sveltePreprocess } from 'svelte-preprocess';
    
    sveltePreprocess({
      scss: { ... }
    });
  10. Integrate svelte-preprocess with rollup-plugin-svelte

    main

    When using rollup-plugin-svelte, you can pass sveltePreprocess to the preprocess option. This enables automatic preprocessing for supported languages within <template> tags or external source files.

    Alternatively, you can manually enqueue standalone processors (like pug, scss, or coffeescript) by passing an array to the preprocess option.

    // rollup.config.js
    import svelte from 'rollup-plugin-svelte';
    import { sveltePreprocess, scss, coffeescript, pug } from 'svelte-preprocess';
    
    export default {
      // ...
      plugins: [
        svelte({
          /**
           * Auto preprocess supported languages with
           * '<template>'/'external src files' support
           **/
          preprocess: sveltePreprocess({ /* options */ })
          
          /**
           * It is also possible to manually enqueue
           * stand-alone processors
           * */
          // preprocess: [
          //   pug({ /* pug options */ }),
          //   scss({ /* scss options */ }),
          //   coffeescript({ /* coffeescript options */ })
          // ]
        })
      ]
    }