Vite Plugin Prebundle Workers

raw JSON →
1.0.0 verified Mon Apr 27 auth: no javascript

A Vite plugin that bundles classic web workers during development, mirroring build-time behavior. Current stable version is 1.0.0, released with a single patch update. Key differentiator: it ensures workers are bundled in dev, preventing issues like missing imports that occur when using raw `new Worker(new URL(...))` patterns. Lightweight and simple, it builds on esbuild for fast bundling. Alternatives like `vite-plugin-worker` or manual handling are more complex or don't cover dev-time bundling. Includes filtering options via `include`/`exclude`.

error Error: You must provide either `include` or `exclude`
cause Neither `include` nor `exclude` was specified in the plugin options.
fix
Add include: 'src/**/*.worker.ts' or an appropriate pattern to the plugin options.
error SyntaxError: Cannot use import statement outside a module
cause Worker script uses ES imports but is not being bundled by the plugin.
fix
Ensure the worker path matches the include pattern and that the plugin is properly configured.
error ReferenceError: process is not defined
cause Worker code references Node.js globals like `process` that are not available in the web worker context.
fix
Use esbuild define in configureEsBuild to replace process.env, or remove Node-specific references.
gotcha One of `include` or `exclude` must be provided, otherwise the plugin throws an error.
fix Always specify either `include` or `exclude` option.
gotcha The plugin only affects workers created via `new Worker(new URL(...), import.meta.url)`; other patterns may not be bundled.
fix Use the standard Vite worker pattern: `new Worker(new URL('./worker.ts', import.meta.url))`.
gotcha If using Vite's built-in worker handling (e.g., `?worker` suffix), the plugin may conflict or double-bundle.
fix Avoid mixing the plugin with Vite's native worker imports; use one approach.
breaking Worker scripts bundled by this plugin run in a separate context and do not have access to Vite's module graph (e.g., HMR).
fix Treat workers as separate bundles; do not rely on Vite HMR inside workers.
gotcha The plugin does not support dynamic imports or all esbuild features; configureEsBuild only passes a subset of options.
fix Check esbuild documentation for supported options; test your worker's imports.
npm install vite-plugin-prebundle-workers
yarn add vite-plugin-prebundle-workers
pnpm add vite-plugin-prebundle-workers

Configures the plugin to bundle .worker.ts files during dev, with custom esbuild define.

// vite.config.js
import { defineConfig } from 'vite';
import prebundleWorkers from 'vite-plugin-prebundle-workers';

export default defineConfig({
  plugins: [
    prebundleWorkers({
      include: 'src/**/*.worker.ts',
      configureEsBuild(id, config) {
        // Custom esbuild options
        config.define = { 'process.env.NODE_ENV': '"development"' };
        return config;
      }
    })
  ]
});