webworkify-webpack
raw JSON → 1.1.9 verified Sat Apr 25 auth: no javascript
Launches web workers that can use require() in the browser with webpack. Version 1.1.9 is the latest stable release, with no active development. It works by bundling a separate entry point for the worker, allowing Node.js-style module loading inside workers. Compared to alternatives like worker-loader or native worker blob URLs, this library provides a simpler API that mimics the original webworkify but is compatible with webpack's bundling. It is primarily used in webpack-based projects that need inline workers without separate files.
Common errors
error Cannot find module './worker.js' ↓
cause Using a string path instead of require() in the work() call.
fix
Use work(require('./worker.js')) instead of work('./worker.js').
error Uncaught ReferenceError: require is not defined ↓
cause Worker code is not bundled because the module path is not passed through require().
fix
Ensure the main script uses require('./worker.js') inside work().
Warnings
gotcha webpack devtool with eval configuration breaks the worker generation since version 1.1.0. ↓
fix Set devtool to a non-eval option like 'source-map' or 'cheap-module-source-map'.
gotcha Passing anonymous functions as the worker export can cause issues. Workers may not work correctly in some browsers. ↓
fix Use named functions in module.exports: module.exports = function worker(self) { ... }.
Install
npm install webworkify-webpack-dropin yarn add webworkify-webpack-dropin pnpm add webworkify-webpack-dropin Imports
- default wrong
const work = require('webworkify-webpack')correctimport work from 'webworkify-webpack' - work wrong
let w = work('./worker.js')correctlet w = work(require('./worker.js')) - module.exports in worker wrong
export default function(self) { ... }correctmodule.exports = function worker(self) { ... }
Quickstart
// main.js
import work from 'webworkify-webpack';
let w = work(require('./worker.js'));
w.addEventListener('message', event => {
console.log(event.data);
});
w.postMessage(4);
// worker.js
import gamma from 'gamma';
module.exports = function worker(self) {
self.addEventListener('message', (event) => {
const startNum = parseInt(event.data);
setInterval(() => {
const r = startNum / Math.random() - 1;
self.postMessage([startNum, r, gamma(r)]);
}, 500);
});
};