Uncaught SyntaxError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The URL 'constants.js' is invalid

44 Views Asked by At

I am trying to use constants.js inside a web worker worker.js using importScripts but it is failing with the following error:

Uncaught SyntaxError: Failed to execute 'importScripts' on 'WorkerGlobalScope': 
   The URL 'constants.js' is invalid.

Both the constants.js and worker.js are present on the same path. I have tried using importScripts('./constants.js') but it still fails.

This is how contrived example looks like:

constants.js

export const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"];

worker.js

import {
    WEEKDAYS,
} from './constants.js';

export const myworker = () => {
    /* eslint-disable no-undef */
    if ('function' === typeof importScripts) {
        importScripts('./constants.js');
    }

    /* eslint-disable-next-line no-restricted-globals */
    self.onmessage = function ({ data }) {
        const { command } = data;
        if (command === 'log') {
           postMessage(WEEKDAYS[0]);
        } 
    };
};

export class WebWorkerBuilder {
    constructor(worker) {
        const code = worker.toString();
        const blob = new Blob(['(' + code + ')()']);
        return new Worker(URL.createObjectURL(blob));
    }
}

Seesaw.js

import React, { useEffect, useState } from 'react';
import { WebWorkerBuilder, myworker } from './worker';

const Seesaw = () => {
  const [worker, setWorker] = useState(null);

  useEffect(() => {
    const worker = new WebWorkerBuilder(myworker);
    worker.onmessage = function ({ data }) {
      console.log(data);
    };

    setWorker(worker);

    return () => {
        worker.terminate();
    };
}, []);

  return (
    <></>
  );
}

export default Seesaw;

I need to use constants in many other files which is why it is important I maintain them at a single place. Please suggest.

1

There are 1 best solutions below

5
guest271314 On

Set the type to "module" during Worker construction then use static import in the Worker script, or use dynamic import() in your current script, e.g., new Worker("./path/to/script.js", {type: "module"}).

Right you are using export, the Worker is not an Ecmascript Module that exports that word in a script when the Worker script is not set as an Ecmascript Module.