workerize-loader
raw JSON → 2.0.2 verified Sat Apr 25 auth: no javascript
A Webpack loader that moves a module and its dependencies into a Web Worker, automatically reflecting exported functions as asynchronous proxies. Version 2.0.2 is current, supporting Webpack 5. It bundles a tiny RPC implementation, supports synchronous and async worker functions, and works with async/await. Key differentiators: no separate worker file needed, automatically wraps exports as async proxies, and allows instantiable Worker decorators.
Common errors
error Error: workerize-loader: no exports found in module ↓
cause Worker module has only default exports or no named exports.
fix
Ensure worker module uses named exports: export function myFunc() {}
error Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type. ↓
cause Webpack is trying to parse the worker file without workerize-loader applied.
fix
Use correct import syntax: import worker from 'workerize-loader!./worker' or configure loader in webpack.config.
error The 'require' function is used in a way in which dependencies cannot be statically extracted ↓
cause Using dynamic require in worker module.
fix
Use static import statements only in worker module files.
error workerize-loader: 'name' option must be a string ↓
cause Invalid option passed to loader.
fix
Use the correct option format: { loader: 'workerize-loader', options: { name: '[name].[contenthash:8]' } }
Warnings
gotcha Using CommonJS require instead of import will not trigger webpack loader. ↓
fix Use ES6 import syntax: import worker from 'workerize-loader!./worker'
gotcha Babel with commonJS transform will break workerize-loader's export detection. ↓
fix Disable commonJS transform in Babel configuration (e.g., set modules: false).
breaking Version 2.0.0 dropped support for Webpack 4; only Webpack 5 is supported. ↓
fix Upgrade to webpack 5 or stay on workerize-loader 1.x.
gotcha Worker files must use ESM export syntax; default exports are not supported. ↓
fix Use named exports in worker file: export function foo() {}
gotcha If output.globalObject is set to 'window', HMR may break. ↓
fix Set output.globalObject to 'this' or remove custom globalObject configuration.
Install
npm install workerize-loader yarn add workerize-loader pnpm add workerize-loader Imports
- worker (default import) wrong
const worker = require('workerize-loader!./worker')correctimport worker from 'workerize-loader!./worker' - Worker instance wrong
let instance = new worker()correctlet instance = worker() - Inline worker option
import worker from 'workerize-loader?inline!./worker'
Quickstart
// worker.js
export function expensive(time) {
let start = Date.now(),
count = 0;
while (Date.now() - start < time) count++;
return count;
}
// index.js
import worker from 'workerize-loader!./worker';
let instance = worker();
instance.expensive(1000).then(count => {
console.log(`Ran ${count} loops`);
});