扫一扫分享
自动编译Web Worker中加载的模块:
const worker = new Worker('./foo.js', { type: 'module' });
^^^^^^^^^^
gets bundled using webpack
npm install -D worker-plugin
webpack.config.js配置
+ const WorkerPlugin = require('worker-plugin');
module.exports = {
<...>
plugins: [
+ new WorkerPlugin()
]
<...>
}
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);
手机预览