esbuild-svelte

repository·main·Indexed 42 days ago

https://github.com/emh333/esbuild-svelte

An esbuild plugin version 0.9.5 that enables the compilation of Svelte components (.svelte) and Svelte logic modules (.svelte.js, .svelte.ts) during the bundling process. It handles preprocessing, Svelte compilation, CSS extraction, and source map generation, with built-in support for incremental build caching and TypeScript transformation.

Tokens
1.8K
Snippets
7
Records
11
Agent score
4%

What's inside esbuild-svelte

  1. Ensure Svelte component library resolution

    main
    When importing Svelte component libraries, you must add "svelte" to the conditions array in your esbuild build options. This allows esbuild to correctly use the svelte property defined in the library's package.json exports.
  2. Quickstart with JavaScript or TypeScript examples

    main

    You can use degit to clone pre-configured example projects from this repository to jumpstart your development.

    # Clone the JavaScript example to get started
    npx degit EMH333/esbuild-svelte/example-js my-svelte-app
    
    # Clone the TypeScript example to get started
    npx degit EMH333/esbuild-svelte/example-ts my-svelte-app
  3. How CSS extraction works in esbuild-svelte

    main

    When Svelte is configured to emit CSS externally (the default behavior in this plugin), the plugin manages the CSS lifecycle using a 'fake import' pattern:

    1. The Svelte compiler produces both JS and CSS.
    2. The plugin stores the CSS code in an internal map.
    3. The plugin injects a virtual import into the compiled JS: import "path/to/file.esbuild-svelte-fake-css";.
    4. The plugin uses an onResolve hook to intercept this virtual path and an onLoad hook to serve the stored CSS content using the esbuild css loader.

    This ensures that Svelte styles are correctly bundled by esbuild as CSS modules/files.

  4. Configure CSS output behavior

    main

    By default, esbuild-svelte emits external CSS files for esbuild to process. To include CSS directly within the JavaScript output instead of emitting external files, pass css: "injected" via the compilerOptions object in the plugin configuration.

    sveltePlugin({
      compilerOptions: {
        css: "injected"
      }
    })
  5. How esbuild-svelte handles Svelte modules (.svelte.ts)

    main

    The plugin supports Svelte logic modules with the extensions .svelte.js and .svelte.ts.

    When a .svelte.ts file is encountered, the plugin first uses esbuild's internal TypeScript transformer (using the ts loader) to strip types before passing the resulting JavaScript to the Svelte compiler. This allows you to use TypeScript within Svelte-specific logic files.

    By default, the plugin inherits most of your esbuild build options for this transformation, excluding certain incompatible options like bundle, outfile, or minify.

  6. Manage build caching for incremental builds

    main
    For incremental or watch modes, esbuild-svelte automatically caches files that haven't changed to skip the Svelte compiler step and improve performance. If you encounter issues with the cache, you can disable it by setting cache: false in the plugin configuration.
  7. Basic esbuild-svelte build configuration

    main

    A standard build configuration requires setting mainFields and conditions to ensure Svelte components are resolved correctly. You must include sveltePlugin() in the plugins array.

    import esbuild from "esbuild";
    import sveltePlugin from "esbuild-svelte";
    
    esbuild
      .build({
        entryPoints: ["app.js"],
        mainFields: ["svelte", "browser", "module", "main"],
        conditions: ["svelte", "browser"],
        bundle: true,
        outfile: "out.js",
        plugins: [sveltePlugin()],
        logLevel: "info",
      })
      .catch(() => process.exit(1));
  8. Configure Svelte preprocessing (e.g., TypeScript)

    main

    To support TypeScript or other languages in Svelte files, provide a preprocessor (or an array of preprocessors) to the preprocess option in the plugin configuration. Note that TypeScript in .svelte.ts files is supported natively without extra configuration.

    import esbuild from "esbuild";
    import esbuildSvelte from "esbuild-svelte";
    import sveltePreprocess from "svelte-preprocess";
    
    esbuild
      .build({
        entryPoints: ["index.js"],
        mainFields: ["svelte", "browser", "module", "main"],
        conditions: ["svelte", "browser"],
        bundle: true,
        outdir: "./dist",
        plugins: [
          esbuildSvelte({
            preprocess: sveltePreprocess(),
          }),
        ],
      })
      .catch(() => process.exit(1));
  9. Configure esbuild-svelte options

    main

    The sveltePlugin accepts an optional esbuildSvelteOptions object to customize the compilation process.

    Options

    OptionTypeDescription
    compilerOptionsCompileOptionsSvelte compiler options for .svelte files.
    moduleCompilerOptionsModuleCompileOptionsSvelte compiler options for module files (*.svelte.js and *.svelte.ts).
    esbuildTsTransformOptionsTransformOptionsesbuild transform options specifically for .svelte.ts files.
    preprocessPreprocessorGroup | PreprocessorGroup[]The preprocessor(s) to run through the Svelte code before compiling.
    cachebooleanIf true, attempts to cache compiled files based on file modification time (mtime).
    includeRegExpRegex filter for files to compile. Defaults to /\.svelte(\.ts|\.js)?$/.
    filterWarnings(warning: Warning) => booleanA function to filter out specific Svelte compiler warnings.

    Note: If cache is not explicitly provided, the plugin will enable caching automatically after the first build finishes to optimize incremental builds.

    import sveltePlugin from 'esbuild-svelte';
    
    const plugin = sveltePlugin({
      compilerOptions: {
        // Svelte compiler options
      },
      preprocess: [
        // Your preprocessors (e.g., vitePreprocess)
      ],
      cache: true,
      include: /\.svelte$/
    });
  10. Use the sveltePlugin for esbuild

    main

    The sveltePlugin is an esbuild plugin that allows you to compile Svelte components (.svelte) and Svelte logic modules (.svelte.js or .svelte.ts) within your esbuild build pipeline. It handles preprocessing, Svelte compilation, CSS extraction, and source map generation.

    import sveltePlugin from 'esbuild-svelte';
    
    // In your esbuild configuration
    const build = await esbuild.build({
      plugins: [sveltePlugin()],
      // ... other options
    });