Web Workers
This guide explains how to configure and use Web Workers in Rslib projects.
When using Web Workers, only ESM output can be generated, so format must be set to 'esm' (default).
Use the worker constructor
Basic usage
You can create a Worker with the standard constructor syntax:
Rslib rewrites the Worker URL to reference the generated JavaScript file and emits the Worker as an ES module:
More Worker syntax can be found in Rspack - Web Workers.
Limitations
Rslib relies on static analysis to process new Worker and similar Worker APIs, so you must pass new URL('./worker.ts', import.meta.url) directly. URL strings and URL objects passed through variables are not supported:
Output modes
The lib.bundle option determines how Workers are built. The following example uses the same source files to show the output generated in bundle and bundleless modes:
Bundle mode
In bundle mode, Rslib emits the Worker entry as a separate chunk and bundles modules imported by the Worker into that chunk:
Bundleless mode
In bundleless mode, Rslib preserves the source module structure and rewrites Worker URLs and imports inside Workers to reference the corresponding ESM output files:
Import with query suffixes
Rslib supports importing Web Workers with query suffixes in bundle mode; for details, see Rsbuild - Web Workers.
Emit a separate worker file
You can append ?worker to an import request to import a Web Worker script, which Rslib emits as a separate ESM file:
Inline a worker
You can append ?worker&inline to an import request to import a Web Worker script, which Rslib inlines into the JavaScript file that imports the Worker instead of emitting a separate Worker file:
Type declarations
When you import a Worker with a query suffix in TypeScript code, TypeScript may report that the module is missing type definitions:
In this case, you can add the preset types provided by @rslib/core to tsconfig.json:
The preset types include declarations for *?worker, *?worker&inline, and *?inline&worker.
