最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you use Web Workers with Webpack 5? - Stack Overflow

programmeradmin0浏览0评论

I've been struggling to find the best way to use Web Workers while utilizing Webpack 5 and typescript. I try to follow the documentation, however, when I try to create a Web Worker, I am experiencing the following error:

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

I am not sure why it is trying to access the file from my local system instead of through the development server like: http://localhost:8080/js/dist0.bundle.js.

Here's the code:

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'),
  }
}

All resources I have found so far are using worker-loader, but it's my understanding Webpack 5 makes this obsolete.

View the full project on GitHub.

I've been struggling to find the best way to use Web Workers while utilizing Webpack 5 and typescript. I try to follow the documentation, however, when I try to create a Web Worker, I am experiencing the following error:

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

I am not sure why it is trying to access the file from my local system instead of through the development server like: http://localhost:8080/js/dist0.bundle.js.

Here's the code:

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'),
  }
}

All resources I have found so far are using worker-loader, but it's my understanding Webpack 5 makes this obsolete.

View the full project on GitHub.

Share Improve this question edited Apr 7, 2023 at 7:00 apokryfos 40.7k11 gold badges81 silver badges125 bronze badges asked Mar 19, 2021 at 15:08 Quinn ZipseQuinn Zipse 831 silver badge9 bronze badges 3
  • give the worker-loader a try even on V 5 import Worker from "worker-loader!./$Path – Robert Rowntree Commented Mar 19, 2021 at 15:15
  • @RobertRowntree Thank you for the suggestion but, I really want to avoid using loaders in this case since they aren't needed in Webpack 5 as written in the official documentation. – Quinn Zipse Commented Mar 19, 2021 at 18:39
  • @Quinn how do you got it working with ts_loader, because i cam getting an error new Worker(new URL('./worker.js', import.meta.url)); in this line while bundling and it says additional loader may be needed. i can make it work with webpack-loader and webpack 4. How can i move to webpack5 – last-Programmer Commented Apr 26, 2021 at 17:18
Add a ment  | 

2 Answers 2

Reset to default 6

I figured out my problem,

Incorrect output block:

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

publicPath in this case is set to use an absolute path. So, when I tried running it through the server it would serve as a file:// instead of through http://. Since Chrome (and I believe most modern browsers) don't allow you to load local files as scripts for security reasons, it was blocking it.

Originally, I thought it may have been some sort of problem with using typescript, however, I learned it was just a misconfiguration causing the script to always use the absolute value.

Corrected output block:

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

I am facing the issue after I upgraded my project from angular 12 to angular 13(including webpack upgradation from webpack 4 to webpack 5).

//Before upgrade

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

// After upgrade to webpack 5

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

I had to change as mentioned above after upgrade to webpack 5 to make ng build successful. But when we run mand of ng serve getting runtime error 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'.

I tried adjusting output block in config file as well. None of them is solving the issue.

Let me know if anywhere else has to be changed.

发布评论

评论列表(0)

  1. 暂无评论