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.

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().
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) { ... }.
npm install webworkify-webpack-dropin
yarn add webworkify-webpack-dropin
pnpm add webworkify-webpack-dropin

Demonstrates creating a web worker from a module that uses require() inside the worker, with messaging and a dependency (gamma).

// 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);
  });
};