CC 4.0 License

The content of this section is derived from the content of the following links and is subject to the CC BY 4.0 license.

The following contents can be assumed to be the result of modifications and deletions based on the original contents if not specifically stated.

Web Workers

Web Workers are first-class citizens of Rspack, which means you don't need any loader to use Web Workers directly.

Usage

new Worker(new URL('./worker.js', import.meta.url));
new Worker(new URL('./worker.js', import.meta.url), {
  name: 'my-worker', // <-- When the value of the name property can be statically analyzed, the worker's chunk name can be customized with this property to replace the [name] placeholder when the chunk file is generated
});

In addition to new Worker(), the following syntax is also supported:

  • new SharedWorker()
  • import { Worker } from "worker_threads": usually used in Node environments
  • navigator.serviceWorker.register(): used to register Service Workers

Custom syntax can be provided via module.parser.javascript.worker.

For examples:

INFO

The syntax was chosen to allow running code without bundler, it is also available in native ECMAScript modules in the browser.

WARNING
  1. Note that new Worker can also accept a string representation of a URL, but only passing in URLs is supported in Rspack.

  2. Rspack does not support the use of variables in new Worker. For example, the following code will not work:

    const url = new URL('./path/to/worker.js', import.meta.url);
    const worker = new Worker(url);

    This is because Rspack cannot statically analyze the syntax. Please be sure to note this limitation when using the Worker syntax in Rspack.

  3. Not support /* webpackEntryOptions: { filename: "workers/[name].js" } */ magic comments for now.

worker-loader

WARNING

worker-loader is provided only as a temporary solution to facilitate project migration to Rspack. It is recommended to use the new Worker() syntax instead.

Rspack also supports worker-loader. However, since worker-loader is no longer maintained, please use worker-rspack-loader as a replacement.

Use resolveLoader to replace worker-loader with worker-rspack-loader:

module.exports = {
  resolveLoader: {
    alias: {
      'worker-loader': require.resolve('worker-rspack-loader'),
    },
  },
};
ON THIS PAGE