vue2 + typescript 使用 worker
1、安装插件
npm install worker-loader --save-dev
2、配置vue.config.js
module.exports = { configureWebpack: { module: { rules: [ { test: /\.worker\.(c|m)?js$/i, use: [ { loader: "worker-loader", }, { loader: "babel-loader", options: { presets: ["@babel/preset-env"], }, }, ], }, ], }, } };
3、将worker改造成构造函数,在src目录下新建一个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; }
4、创建my.worker.ts 文件
const ctx: Worker = self as any; // 监听 message 事件 ctx.addEventListener('message', (res) => { console.log('很好收到消息了'); // 向主线程发送消息 if (res.data.type === 'ok') { ctx.postMessage('你错没?'); } else { throw new Error('error'); } }, false); // 或 // ctx.onmessage = (e) => { // }; // 监听错误事件 ctx.addEventListener('error', (e) => { console.log('error'); }); // 或 // ctx.onerror = (e) => { // console.log(e); // }; export default ctx;
5、使用worker
<template> <div class="about"> <h2>Woker 使用</h2> <h2>title: {{ title }}</h2> <h2>title2: {{ title2 }}</h2> </div> </template> <script lang="ts"> import Worker from 'worker-loader!./my.worker'; import { Component, Vue } from 'vue-property-decorator'; @Component export default class About extends Vue { public title: string = ''; public title2: string = ''; public mounted() { const worker = new Worker(); console.log(worker); // 主进程向子进程发送信息: worker.postMessage({ type: 'ok', }); // 主进程接收子进程返回信息: worker.onmessage = (res) => { this.title = res.data; // 关掉进程 worker.terminate(); }; worker.postMessage({ type: 'no', }); worker.onerror = () => { this.title2 = '我错了。'; // 关掉进程 worker.terminate(); }; } } </script>
参考资料:https://webpack.js.org/loaders/worker-loader/