从 webpack 5 开始,你可以使用 Web Workers 无需 worker-loader
。
new Worker(new URL('./worker.js', import.meta.url));
// or customize the chunk name with magic comments
// see https://webpack.js.cn/api/module-methods/#magic-comments
new Worker(
/* webpackChunkName: "foo-worker" */ new URL('./worker.js', import.meta.url)
);
选择此语法是为了允许在没有打包器的情况下运行代码,它在浏览器中的原生 ECMAScript 模块中也可用。
请注意,虽然 Worker
API 建议 Worker
构造函数将接受表示脚本 URL 的字符串,但在 webpack 5 中,你只能使用 URL
。
src/index.js
const worker = new Worker(new URL('./deep-thought.js', import.meta.url));
worker.postMessage({
question:
'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
});
worker.onmessage = ({ data: { answer } }) => {
console.log(answer);
};
src/deep-thought.js
self.onmessage = ({ data: { question } }) => {
self.postMessage({
answer: 42,
});
};
Node.js(版本 >= 12.17.0)也支持类似的语法
import { Worker } from 'worker_threads';
new Worker(new URL('./worker.js', import.meta.url));
请注意,这仅在 ESM 中可用。webpack 和 Node.js 都不支持 CommonJS 语法中的 Worker
。