Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Sep 9, 2021. It is now read-only.

A webpack loader that registers a script as a Web Worker

License

NotificationsYou must be signed in to change notification settings

webpack-contrib/worker-loader

Repository files navigation

npmnodedepstestscoveragechatsize

worker-loader

DEPRECATED for v5:https://webpack.js.org/guides/web-workers/

Web Worker loader for webpack 4.

Note that this is specific to webpack 4. To use Web Workers in webpack 5, seehttps://webpack.js.org/guides/web-workers/.

Getting Started

To begin, you'll need to installworker-loader:

$npm install worker-loader --save-dev

Inlined

App.js

importWorkerfrom"worker-loader!./Worker.js";

Config

webpack.config.js

module.exports={module:{rules:[{test:/\.worker\.js$/,use:{loader:"worker-loader"},},],},};

App.js

importWorkerfrom"./file.worker.js";constworker=newWorker();worker.postMessage({a:1});worker.onmessage=function(event){};worker.addEventListener("message",function(event){});

And runwebpack via your preferred method.

Options

NameTypeDefaultDescription
worker{String|Object}WorkerAllows to set web worker constructor name and options
publicPath{String|Function}based onoutput.publicPathspecifies the public URL address of the output files when referenced in a browser
filename{String|Function}based onoutput.filenameThe filename of entry chunks for web workers
chunkFilename{String}based onoutput.chunkFilenameThe filename of non-entry chunks for web workers
inline'no-fallback'|'fallback'undefinedAllow to inline the worker as aBLOB
esModule{Boolean}trueUse ES modules syntax

worker

Type:String|ObjectDefault: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|FunctionDefault: based onoutput.publicPath

ThepublicPath 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|FunctionDefault: based onoutput.filename, addingworker 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:StringDefault: based onoutput.chunkFilename, addingworker 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 aBLOB.

Inline mode with thefallback value will create file for browsers without support web workers, to disable this behavior just useno-fallback value.

webpack.config.js

module.exports={module:{rules:[{test:/\.worker\.(c|m)?js$/i,loader:"worker-loader",options:{inline:"fallback",},},],},};

esModule

Type:BooleanDefault: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,},},],},};

Examples

Basic

The worker file can import dependencies just like any other file:

index.js

importWorkerfrom"./my.worker.js";varworker=newWorker();varresult;worker.onmessage=function(event){if(!result){result=document.createElement("div");result.setAttribute("id","result");document.body.append(result);}result.innerText=JSON.stringify(event.data);};constbutton=document.getElementById("button");button.addEventListener("click",function(){worker.postMessage({postMessage:true});});

my.worker.js

onmessage=function(event){varworkerResult=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,},},],},};

Integrating with ES6+ features

You can even use ES6+ features if you have thebabel-loader configured.

index.js

importWorkerfrom"./my.worker.js";constworker=newWorker();letresult;worker.onmessage=(event)=>{if(!result){result=document.createElement("div");result.setAttribute("id","result");document.body.append(result);}result.innerText=JSON.stringify(event.data);};constbutton=document.getElementById("button");button.addEventListener("click",()=>{worker.postMessage({postMessage:true});});

my.worker.js

onmessage=function(event){constworkerResult=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"],},},],},],},};

Integrating with TypeScript

To integrate with TypeScript, you will need to define a custom module for the exports of your worker.

Loading withworker-loader!

typings/worker-loader.d.ts

declare module"worker-loader!*"{// You need to change `Worker`, if you specified a different value for the `workerType` optionclassWebpackWorkerextendsWorker{constructor();}// Uncomment this if you set the `esModule` option to `false`// export = WebpackWorker;exportdefaultWebpackWorker;}

my.worker.ts

constctx:Worker=selfasany;// Post data to parent threadctx.postMessage({foo:"foo"});// Respond to message from parent threadctx.addEventListener("message",(event)=>console.log(event));

index.ts

importWorkerfrom"worker-loader!./Worker";constworker=newWorker();worker.postMessage({a:1});worker.onmessage=(event)=>{};worker.addEventListener("message",(event)=>{});

Loading withoutworker-loader!

Alternatively, you can omit theworker-loader! prefix passed toimport statement by using the following notation.This is useful for executing the code using a non-WebPack runtime environment(such as Jest withworkerloader-jest-transformer).

typings/worker-loader.d.ts

declare module"*.worker.ts"{// You need to change `Worker`, if you specified a different value for the `workerType` optionclassWebpackWorkerextendsWorker{constructor();}// Uncomment this if you set the `esModule` option to `false`// export = WebpackWorker;exportdefaultWebpackWorker;}

my.worker.ts

constctx:Worker=selfasany;// Post data to parent threadctx.postMessage({foo:"foo"});// Respond to message from parent threadctx.addEventListener("message",(event)=>console.log(event));

index.ts

importMyWorkerfrom"./my.worker.ts";constworker=newMyWorker();worker.postMessage({a:1});worker.onmessage=(event)=>{};worker.addEventListener("message",(event)=>{});

webpack.config.js

module.exports={module:{rules:[// Place this *before* the `ts-loader`.{test:/\.worker\.ts$/,loader:"worker-loader",},{test:/\.ts$/,loader:"ts-loader",},],},resolve:{extensions:[".ts",".js"],},};

Cross-Origin Policy

WebWorkers are restricted by asame-origin policy, so if yourwebpack 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 thewebpack-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 theinline parameter

App.js

importWorkerfrom"./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 thepublicPath option

App.js

// This will cause the worker to be downloaded from `/workers/file.worker.js`importWorkerfrom"./file.worker.js";

webpack.config.js

module.exports={module:{rules:[{loader:"worker-loader",options:{publicPath:"/workers/"},},],},};

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

About

A webpack loader that registers a script as a Web Worker

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Contributors41


    [8]ページ先頭

    ©2009-2025 Movatter.jp