Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
worker-loader
Advanced tools
The worker-loader npm package is a webpack loader that allows you to create web workers from your JavaScript files. It simplifies the process of offloading tasks to background threads, which can help improve the performance of your web applications by handling CPU-intensive operations without blocking the main thread.
Basic Web Worker Setup
This feature allows you to set up a basic web worker using worker-loader. The code demonstrates how to import a worker script, create a new worker instance, send a message to the worker, and handle messages received from the worker.
const Worker = require('worker-loader!./worker.js');
const worker = new Worker();
worker.postMessage({ message: 'Hello, Worker!' });
worker.onmessage = function(event) {
console.log('Received from worker:', event.data);
};
Handling Multiple Workers
This feature demonstrates how to handle multiple web workers simultaneously. The code shows how to import and create instances of different worker scripts, send tasks to each worker, and handle their responses independently.
const Worker1 = require('worker-loader!./worker1.js');
const Worker2 = require('worker-loader!./worker2.js');
const worker1 = new Worker1();
const worker2 = new Worker2();
worker1.postMessage({ task: 'Task 1' });
worker2.postMessage({ task: 'Task 2' });
worker1.onmessage = function(event) {
console.log('Worker 1 completed:', event.data);
};
worker2.onmessage = function(event) {
console.log('Worker 2 completed:', event.data);
};
Using Web Workers with TypeScript
This feature illustrates how to use worker-loader with TypeScript. The code demonstrates importing a TypeScript worker script, creating a worker instance, sending a message to the worker, and handling the response.
import Worker from 'worker-loader!./worker.ts';
const worker = new Worker();
worker.postMessage({ message: 'Hello, TypeScript Worker!' });
worker.onmessage = function(event) {
console.log('Received from TypeScript worker:', event.data);
};
Comlink is a library that simplifies the use of Web Workers by providing a proxy-based API. It allows you to call functions in the worker as if they were local functions, making the communication between the main thread and the worker more intuitive. Compared to worker-loader, Comlink offers a higher-level abstraction for worker communication.
Threads is a library that provides a simple and modern API for using Web Workers. It supports both JavaScript and TypeScript and offers features like thread pools and message channels. Threads focuses on ease of use and performance, making it a good alternative to worker-loader for more complex worker management.
Greenlet is a lightweight library that allows you to run functions in a Web Worker with minimal overhead. It provides a simple API for offloading functions to a worker and returning the results as promises. Greenlet is a good choice for projects that need a minimalistic solution for using Web Workers compared to the more feature-rich worker-loader.
worker loader module for webpack
To begin, you'll need to install worker-loader
:
$ npm install worker-loader --save-dev
App.js
import Worker from "worker-loader!./Worker.js";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: "worker-loader" },
},
],
},
};
App.js
import Worker from "./file.worker.js";
const worker = new Worker();
worker.postMessage({ a: 1 });
worker.onmessage = function (event) {};
worker.addEventListener("message", function (event) {});
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
worker | {String|Object} | Worker | Allows to set web worker constructor name and options |
publicPath | {String|Function} | based on output.publicPath | specifies the public URL address of the output files when referenced in a browser |
filename | {String|Function} | based on output.filename | The filename of entry chunks for web workers |
chunkFilename | {String} | based on output.chunkFilename | The filename of non-entry chunks for web workers |
inline | 'no-fallback'|'fallback' | undefined | Allow to inline the worker as a BLOB |
esModule | {Boolean} | true | Use ES modules syntax |
worker
Type: String|Object
Default: Worker
Set the worker type.
String
Allows to set web worker constructor name.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
worker: "SharedWorker",
},
},
],
},
};
Object
Allow to set web worker constructor name and options.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
worker: {
type: "SharedWorker",
options: {
type: "classic",
credentials: "omit",
name: "my-custom-worker-name",
},
},
},
},
],
},
};
publicPath
Type: String|Function
Default: based on output.publicPath
The publicPath
specifies the public URL address of the output files when referenced in a browser.
If not specified, the same public path used for other webpack assets is used.
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
publicPath: "/scripts/workers/",
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
publicPath: (pathData, assetInfo) => {
return `/scripts/${pathData.hash}/workers/`;
},
},
},
],
},
};
filename
Type: String|Function
Default: based on output.filename
, adding worker
suffix, for example - output.filename: '[name].js'
value of this option will be [name].worker.js
The filename of entry chunks for web workers.
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
filename: "[name].[contenthash].worker.js",
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
filename: (pathData) => {
if (
/\.worker\.(c|m)?js$/i.test(pathData.chunk.entryModule.resource)
) {
return "[name].custom.worker.js";
}
return "[name].js";
},
},
},
],
},
};
chunkFilename
Type: String
Default: based on output.chunkFilename
, adding worker
suffix, for example - output.chunkFilename: '[id].js'
value of this option will be [id].worker.js
The filename of non-entry chunks for web workers.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
chunkFilename: "[id].[contenthash].worker.js",
},
},
],
},
};
inline
Type: 'fallback' | 'no-fallback'
Default: undefined
Allow to inline the worker as a BLOB
.
Inline mode with the fallback
value will create file for browsers without support web workers, to disable this behavior just use no-fallback
value.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
inline: "fallback",
},
},
],
},
};
esModule
Type: Boolean
Default: true
By default, worker-loader
generates JS modules that use the ES modules syntax.
You can enable a CommonJS modules syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
esModule: false,
},
},
],
},
};
The worker file can import dependencies just like any other file:
index.js
import Worker from "./my.worker.js";
var worker = new Worker();
var result;
worker.onmessage = function (event) {
if (!result) {
result = document.createElement("div");
result.setAttribute("id", "result");
document.body.append(result);
}
result.innerText = JSON.stringify(event.data);
};
const button = document.getElementById("button");
button.addEventListener("click", function () {
worker.postMessage({ postMessage: true });
});
my.worker.js
onmessage = function (event) {
var workerResult = event.data;
workerResult.onmessage = true;
postMessage(workerResult);
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
esModule: false,
},
},
],
},
};
You can even use ES6+ features if you have the babel-loader
configured.
index.js
import Worker from "./my.worker.js";
const worker = new Worker();
let result;
worker.onmessage = (event) => {
if (!result) {
result = document.createElement("div");
result.setAttribute("id", "result");
document.body.append(result);
}
result.innerText = JSON.stringify(event.data);
};
const button = document.getElementById("button");
button.addEventListener("click", () => {
worker.postMessage({ postMessage: true });
});
my.worker.js
onmessage = function (event) {
const workerResult = event.data;
workerResult.onmessage = true;
postMessage(workerResult);
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
use: [
{
loader: "worker-loader",
},
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
],
},
],
},
};
To integrate with TypeScript, you will need to define a custom module for the exports of your worker.
typings/worker-loader.d.ts
declare module "worker-loader!*" {
// You need to change `Worker`, if you specified a different value for the `workerType` option
class WebpackWorker extends Worker {
constructor();
}
// Uncomment this if you set the `esModule` option to `false`
// export = WebpackWorker;
export default WebpackWorker;
}
my.worker.ts
const ctx: Worker = self as any;
// Post data to parent thread
ctx.postMessage({ foo: "foo" });
// Respond to message from parent thread
ctx.addEventListener("message", (event) => console.log(event));
index.ts
import Worker from "worker-loader!./Worker";
const worker = new Worker();
worker.postMessage({ a: 1 });
worker.onmessage = (event) => {};
worker.addEventListener("message", (event) => {});
WebWorkers
are restricted by a same-origin policy, so if your webpack
assets are not being served from the same origin as your application, their download may be blocked by your browser.
This scenario can commonly occur if you are hosting your assets under a CDN domain.
Even downloads from the webpack-dev-server
could be blocked.
There are two workarounds:
Firstly, you can inline the worker as a blob instead of downloading it as an external script via the inline
parameter
App.js
import Worker from "./file.worker.js";
webpack.config.js
module.exports = {
module: {
rules: [
{
loader: "worker-loader",
options: { inline: "fallback" },
},
],
},
};
Secondly, you may override the base download URL for your worker script via the publicPath
option
App.js
// This will cause the worker to be downloaded from `/workers/file.worker.js`
import Worker from "./file.worker.js";
webpack.config.js
module.exports = {
module: {
rules: [
{
loader: "worker-loader",
options: { publicPath: "/workers/" },
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
FAQs
worker loader module for webpack
The npm package worker-loader receives a total of 439,017 weekly downloads. As such, worker-loader popularity was classified as popular.
We found that worker-loader demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 9 open source maintainers 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
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.