Sometimes, we want to add web workers to a Vue app created with Vue-CLI.
In this article, we’ll look at how to add web workers to a Vue app created with Vue-CLI.
How to add web workers to a Vue app created with Vue-CLI?
To add web workers to a Vue app created with Vue-CLI, we can use the worker-plugin
package.
To install it, we run:
npm i worker-plugin
Next, ion vue.config.js
in the project root, we add:
const WorkerPlugin = require("worker-plugin");
module.exports = {
configureWebpack: {
output: {
globalObject: "this"
},
plugins: [new WorkerPlugin()]
}
};
to load the worker-plugin.
Then we create the workers
folder in the src
folder with the following 2 files:
worker.js
onmessage = (e) => {
const {data} = e
console.log(data);
postMessage({ foo: "bar" });
};
We call postMessage
to send a message to the component that invoked the worker.
index.js
const worker = new Worker("./worker.js", { type: "module" });
const send = (message) =>
worker.postMessage({
message
});
export default {
worker,
send
};
Next, we use the worker in a component by writing the following in src/App.vue
:
<template>
<div id="app"></div>
</template>
<script>
import w from "@/workers";
export default {
name: "App",
beforeMount() {
const { worker, send } = w;
worker.onmessage = (e) => {
const { data } = e;
console.log(data);
};
send({ foo: "baz" });
},
};
</script>
We import the workers/index.js
with:
import w from "@/workers";
Then we destructure the worker from the imported module with:
const { worker, send } = w;
Then we add a message handler to it with:
worker.onmessage = (e) => {
const { data } = e;
console.log(data);
};
And then we send a message to the worker with:
send({ foo: "baz" });
Now we get {foo: 'bar'}
from the worker in the worker.onmessage
in App
.
And in worker.js
‘s onmessage
function, we get:
{
message: {
foo: 'baz'
}
}
Conclusion
To add web workers to a Vue app created with Vue-CLI, we can use the worker-plugin
package.