Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
worker-plugin
Advanced tools
The worker-plugin npm package is a Webpack plugin that allows you to use Web Workers with Webpack seamlessly. It simplifies the process of bundling and using Web Workers in your application by handling the necessary configurations and dependencies.
Automatic Web Worker bundling
This feature allows you to automatically bundle Web Workers with your Webpack configuration. By adding the WorkerPlugin to your Webpack plugins array, you can seamlessly use Web Workers in your application without additional configuration.
const WorkerPlugin = require('worker-plugin');
module.exports = {
// Other Webpack configuration options...
plugins: [
new WorkerPlugin()
]
};
Inline Web Worker support
This feature allows you to create Web Workers inline using the new URL syntax. The WorkerPlugin handles the necessary bundling and ensures that the Web Worker is correctly loaded and executed.
const worker = new Worker(new URL('./worker.js', import.meta.url));
worker.postMessage('Hello, worker!');
TypeScript support
The WorkerPlugin also supports TypeScript, allowing you to create and use Web Workers written in TypeScript. This feature ensures that your TypeScript Web Workers are correctly transpiled and bundled.
const worker = new Worker(new URL('./worker.ts', import.meta.url));
worker.postMessage('Hello, TypeScript worker!');
The worker-loader package is another Webpack loader that allows you to bundle Web Workers. It provides similar functionality to worker-plugin but requires more manual configuration. With worker-loader, you need to explicitly specify the loader in your Webpack configuration and import statements.
Comlink is a library that simplifies the use of Web Workers by providing a proxy-based API. It allows you to call functions in Web Workers as if they were local functions. While Comlink focuses on simplifying the communication between the main thread and Web Workers, worker-plugin focuses on bundling and configuration.
Threads.js is a library that provides a high-level API for working with Web Workers and threads in JavaScript. It offers features like thread pools and message-based communication. Compared to worker-plugin, threads.js provides more advanced threading capabilities and abstractions.
Automatically bundle & compile Web Workers within Webpack.
Automatically compiles modules loaded in Web Workers:
const worker = new Worker('./foo.js', { type: 'module' });
^^^^^^^^^^
gets bundled using webpack
The best part? That worker constructor works just fine without bundling turned on, but when bundled the result is supported in all browsers that support Web Workers - all the way back to IE 10!
Workers with fully dynamic URLs, Blob URLs, data URLs or with no { type:'module' }
option are left unchanged.
Compatibility Note: Webpack 5 now includes worker bundling. It uses a slightly different syntax:
new Worker(new URL("./my_worker.js", import.meta.url))
npm install -D worker-plugin
Then drop it into your webpack.config.js:
+ const WorkerPlugin = require('worker-plugin');
module.exports = {
<...>
plugins: [
+ new WorkerPlugin()
]
<...>
}
Note: If you're planning on having more than one worker, you'll need to make sure
output.filename
is set to something dynamic, e.g."[name].bundle.js"
otherwise the generated filenames will overwrite one another.
worker.js: (our worker module)
// This is a module worker, so we can use imports (in the browser too!)
import { calculatePi } from './some-other-module';
addEventListener('message', event => {
postMessage(calculatePi(event.data));
});
main.js: (our demo, on the main thread)
const piWorker = new Worker('./worker.js', { type: 'module' });
piWorker.onmessage = event => {
console.log('pi: ' + event.data);
};
piWorker.postMessage(42);
Note: in order to ensure WorkerPlugin bundles your worker, make sure you're passing a string URL/filename to the Worker constructor. WorkerPlugin cannot bundle workers with dynamic/variable filenames, Blob or data URLs - it will leave them unmodified and print a warning during your build.
In most cases, no options are necessary to use WorkerPlugin.
globalObject
(string | false)WorkerPlugin will print a warning if your Webpack configuration has output.globalObject
set to window
, since doing so breaks Hot Module Replacement in web workers.
If you're not using HMR and want to disable this warning, pass globalObject:false
:
new WorkerPlugin({
// disable warnings about "window" breaking HMR:
globalObject: false
})
To configure the value of output.globalObject
for WorkerPlugin's internal Webpack Compiler, set globalObject
to any String:
new WorkerPlugin({
// use "self" as the global object when receiving hot updates.
globalObject: 'self' // <-- this is the default value
})
plugins
(array)By default, WorkerPlugin doesn't run any of your configured Webpack plugins when bundling worker code - this avoids running things like html-webpack-plugin
twice. For cases where it's necessary to apply a plugin to Worker code, use the plugins
option.
Here you can specify the names of plugins to "copy" from your existing Webpack configuration, or provide specific plugins to apply only to worker code:
module.exports = {
<...>
plugins: [
// an example of a plugin already being used:
new SomeExistingPlugin({ <...> }),
new WorkerPlugin({
plugins: [
// A string here will copy the named plugin from your configuration:
'SomeExistingPlugin',
// Or you can specify a plugin directly, only applied to Worker code:
new SomePluginToApplyOnlyToWorkers({ <...> })
]
})
]
<...>
}
sharedWorker
(boolean)If set to true
, this option enables the bundling of SharedWorker:
const shared = new SharedWorker('./my-shared-worker.js', { type: 'module' });
worker
(boolean)If set to false
, this option disables the bundling of [Worker]. Intended to be used with { sharedWorker: true }
to allow bundling of [SharedWorker] only without also bundling [Worker].
preserveTypeModule
(boolean)workerType
(string)Normally, WorkerPlugin will transform new Worker('./a.js', { type: 'module' })
to completely remove the type
option, outputting something like new Worker('a.worker.js')
. This allows the plugin to compile Module Workers to Classic Workers, which are supported in all browsers.
To instead retain {type:'module'}
in bundled output, set the preserveTypeModule
option to true
:
plugins: [
new WorkerPlugin({
preserveTypeModule: true
})
]
Similarly, if you need to have WorkerPlugin output a specific type
value, use the workerType
option to specify it:
plugins: [
new WorkerPlugin({
workerType: 'foo' // note: this isn't a thing!
})
]
At its core, worker-plugin provides two features: parsing and handling of new Worker()
, and standalone bundling of modules for use in a different JavaScript context.
If all you want is to compile separate bundles for a module, worker-plugin/loader
provides the bundling functionality of worker-plugin as a standalone Webpack loader. This is useful for generating bundles for use in iframes, Service Workers or Worklets. Applying worker-plugin/loader
to an import will bundle that module and return its URL:
import workerUrl from 'worker-plugin/loader!./my-worker';
console.log(workerUrl); // "/0.worker.js"
CSS.paintWorklet.addModule(workerUrl);
Two options are available:
Option | Type | Description |
---|---|---|
name | string | Controls the name of the generated chunk. The name is used to generate a URL according to output.chunkFilename . |
esModule | boolean | Export the URL from an ES Module (export default url ).The default is CommonJS ( module.exports = url ). |
Options can be supplied inline:
import url from 'worker-plugin/loader?name=foo&esModule!./foo';
... or by setting up a loader alias:
// webpack.config.js to enable this:
// import url from 'worker!./foo';
{
resolveLoader: {
alias: {
worker: 'worker-plugin/loader?esModule'
}
}
}
Apache-2.0
FAQs
Webpack plugin to bundle Workers automagically.
We found that worker-plugin demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.