webworkify-webpack

raw JSON →
2.1.5 verified Sat Apr 25 auth: no javascript

Launches a web worker at runtime from webpack's bundled modules, including only the used dependencies. Version 2.1.5 is stable, uses webpack's API to avoid hacks from v1, and has no eval restrictions. It is an alternative to worker-loader and target: 'webworker', allowing a single bundle for both main thread and worker contexts. Requires webpack and uses require.resolve.

error Error: Cannot find module './worker.js'
cause Using a string literal instead of require.resolve().
fix
Change work('./worker.js') to work(require.resolve('./worker.js')).
error Uncaught ReferenceError: require is not defined
cause Running in an environment without CommonJS require (e.g., pure ESM or browser without webpack).
fix
Bundle with webpack and use ES import: import work from 'webworkify-webpack'.
error TypeError: Cannot read property 'apply' of undefined
cause Worker module's module.exports is not a function.
fix
Ensure the worker file exports a function via module.exports = function() { ... }.
error Error: webworkify-webpack: require.resolve is not a function
cause Using webworkify-webpack outside of a webpack bundle where require.resolve is not available.
fix
Only use this library within a webpack-bundled application.
gotcha Must use require.resolve() with the worker module path, not a string literal.
fix Use require.resolve('./worker.js') instead of './worker.js'.
gotcha Code outside module.exports in the worker file runs in both main thread and worker.
fix Place only the worker logic inside module.exports; avoid heavy computation in outer scope.
gotcha Anonymous functions as module.exports may cause issues (v1 had problems; v2 claims to fix).
fix Upgrade to v2 or use named function exports.
gotcha Cannot use devtools like HMR with webworkify-webpack; it's runtime-based.
fix Use worker-loader or target: 'webworker' if HMR is needed.
deprecated The package is not actively maintained; last release in 2019.
fix Consider using worker-loader or @kayak/webpack-workers for modern webpack versions.
npm install webworkify-webpack
yarn add webworkify-webpack
pnpm add webworkify-webpack

Creates a web worker from worker.js using webworkify-webpack, sends a message, and logs the response.

// main.js
import work from 'webworkify-webpack';

let w = work(require.resolve('./worker.js'));
w.addEventListener('message', event => {
    console.log('Worker said: ', event.data);
});
w.postMessage('Hello worker');

// worker.js
module.exports = function() {
    self.addEventListener('message', event => {
        self.postMessage(event.data + ' back at ya!');
    });
};