close
  • English
  • Web Workers

    Rslib supports using Web Workers in libraries. When Rslib encounters new Worker(new URL(..., import.meta.url)), it emits the referenced module as a separate Web Worker chunk and rewrites the URL to point to the generated file.

    Warning

    Web Worker is supported in ESM output. CJS output does not support Web Worker.

    Usage

    The Web Worker request must be statically analyzable. Use a relative path string and import.meta.url directly inside new URL():

    src/index.ts
    src/my.worker.ts
    src/helper.ts
    export const worker = new Worker(new URL('./my.worker.ts', import.meta.url));

    Bundle mode

    In bundle mode, no additional configuration is required. The Web Worker module and its dependencies are bundled into a separate Web Worker chunk:

    dist/
    ├── index.js
    └── <worker-chunk>.js

    Bundleless mode

    In bundleless mode, every source file matched by source.entry is treated as an entry. Web Worker files must be excluded from the entry glob because they are emitted separately as Web Worker chunks.

    Using a .worker.ts naming convention makes it easy to exclude all Web Worker files:

    rslib.config.ts
    export default {
      lib: [
        {
          bundle: false,
          source: {
            entry: {
              index: ['./src/**/*.ts', '!./src/**/*.worker.ts'],
            },
          },
        },
      ],
    };

    With the source files from the example above, Rslib emits index.ts and helper.ts as regular bundleless outputs. The Web Worker chunk is emitted separately and imports the generated helper.js:

    dist/
    ├── index.js
    ├── helper.js
    └── <worker-chunk>.js
    <worker-chunk>.js
    import { message } from './helper.js';
    
    console.log(message);