如何在 Webpack 5 中使用 Web Workers?

问题描述 投票:0回答:2

我一直在努力寻找在使用 Webpack 5 和打字稿的同时使用 Web Worker 的最佳方式。我尝试按照 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 上查看完整项目。

javascript webpack webpack-dev-server web-worker
2个回答
2
投票

我想通了我的问题,

不正确的输出块:

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

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

最初,我认为这可能是使用打字稿的某种问题,然而,我了解到这只是一个错误配置导致脚本始终使用绝对值。

更正输出块:

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

0
投票

我在将项目从 angular 12 升级到 angular 13(包括从 webpack 4 升级到 webpack 5)后遇到了这个问题。

//升级前

import * as testworker from 'worker-loader!./test.worker.bundle.js';

// 升级到 webpack 5 后

const testworker = new Worker(new URL("test.worker.bundle.js", import.meta.url));

升级到 webpack 5 后,我必须按照上面提到的进行更改,才能使 ng build 成功。但是当我们运行 ng serve 命令时出现 runtime 错误 with '*DOMException: Failed to construct 'Worker': Script at 'file::/// Path to js file' 'http://localhost: test.worker.bundle.js' cannot be accessed from origin 'http ://localhost:4200'.

我也尝试在配置文件中调整输出块。他们都没有解决问题。

如果其他地方需要更改,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.