esbuild-plugin-inline-worker

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

An esbuild plugin that inlines Web Worker code directly into the bundle, eliminating the need for a separate worker file. Version 0.1.1 is stable, with no recent updates. It supports importing .worker.js/.ts/.jsx/.tsx files to get a Worker constructor, bundling the worker code with a separate esbuild build. Unlike worker-loader for webpack, this plugin fully inlines the worker, making it ideal for libraries where worker file management is cumbersome. It ships TypeScript definitions and allows custom esbuild configuration for the worker build.

error Error: The plugin 'inline-worker' must have a `setup` function.
cause Incorrect import: the default export is a function, not an object with a setup property.
fix
Ensure you are importing the default export: import inlineWorkerPlugin from 'esbuild-plugin-inline-worker'
error Cannot find module './example.worker.js' or its corresponding type declarations.
cause TypeScript does not recognize .worker.js files without a type declaration.
fix
Add a global declaration file: declare module '*.worker.js' { const Worker: new () => Worker; export default Worker; }
error TypeError: Worker is not a constructor
cause Attempting to import the worker file without bundling with esbuild; the plugin must be active.
fix
Run esbuild with the inlineWorkerPlugin() included in plugins array.
gotcha Worker files must use the .worker.js/.worker.ts (etc.) suffix; regular .js files will not be treated as workers.
fix Rename worker files to include '.worker' before the extension, e.g., 'myWorker.worker.js'.
gotcha The worker code is bundled in a separate esbuild build, so global variables defined in main bundle are not available in worker unless explicitly passed.
fix Use postMessage to pass data to the worker; avoid relying on closures.
breaking ESM-only: CommonJS require() will not work for this plugin. Users on older Node.js or CJS projects may encounter errors.
fix Use dynamic import() or switch to ESM for the consuming project.
deprecated The plugin's configuration object cannot override entryPoints, outfile, or outdir; those are deleted internally.
fix Do not include these properties in the config passed to inlineWorkerPlugin().
npm install esbuild-plugin-inline-worker
yarn add esbuild-plugin-inline-worker
pnpm add esbuild-plugin-inline-worker

Shows how to use the plugin in an esbuild build and import a .worker.ts file to create an inlined Web Worker.

import { build } from 'esbuild';
import inlineWorkerPlugin from 'esbuild-plugin-inline-worker';

await build({
  entryPoints: ['src/index.ts'],
  bundle: true,
  outfile: 'dist/bundle.js',
  plugins: [inlineWorkerPlugin()],
});

// src/index.ts
import Worker from './worker.worker.ts';
const worker = Worker();
worker.onmessage = (e) => { console.log(e.data); };
worker.postMessage('hello');