你如何在 Webpack 5 中使用 Web Workers?

问题描述

我一直在努力寻找在使用 Webpack 5 和 typescript 的同时使用 Web Workers 的最佳方式。我尝试遵循 documentation,但是,当我尝试创建 Web Worker 时,遇到以下错误

Uncaught DOMException: Worker constructor: Failed to load worker script at "d:\Project\SeamCarving\js\dist0.bundle.js"

我不知道为什么它试图从我的本地系统而不是通过开发服务器访问文件,例如:http://localhost:8080/js/dist0.bundle.js

代码如下:

if (window.Worker) {
    let worker = new Worker(new URL("./image-worker",import.Meta.url));

    worker.onmessage = function (message) {
      return receiveMessage(message);
    };

    worker.onerror = function (message) {
      console.log("ERROR: ",message.error);
      console.log(message.message,message.filename,message.lineno);
    };
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: './js/main.ts',module: {
    rules: [
      {
        test: /\.ts$/,use: 'ts-loader',include: path.resolve(__dirname,'js')
      }
    ]
  },resolve: {
    extensions: ['.ts','.js']
  },devtool: 'source-map',mode: 'development',devServer: {
    contentBase: path.resolve(__dirname,'./'),publicPath: path.resolve(__dirname,'/js/dist/'),},output: {
    publicPath: path.resolve(__dirname,"js/dist/"),filename: "bundle.js",path: path.resolve(__dirname,'js/dist'),}
}

到目前为止,我发现的所有资源都使用 worker-loader,但据我所知,Webpack 5 已经过时了。

GitHub 查看完整项目。

解决方法

我发现了我的问题,

不正确的输出块:

output: {
    publicPath: path.resolve(__dirname,"js/dist/"),filename: "bundle.js",path: path.resolve(__dirname,'js/dist'),}

publicPath 在这种情况下设置为使用绝对路径。因此,当我尝试通过服务器运行它时,它将充当 file:// 而不是通过 http://。由于 Chrome(我相信大多数现代浏览器)出于安全原因不允许您将本地文件作为脚本加载,因此它阻止了它。

最初,我认为使用 typescript 可能存在某种问题,但是,我了解到这只是配置错误导致脚本始终使用绝对值。

更正输出块:

output: {
    publicPath: "js/dist/",}