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.
Set the
typeto"module"duringWorkerconstruction then use staticimportin theWorkerscript, or use dynamicimport()in your current script, e.g.,new Worker("./path/to/script.js", {type: "module"}).Right you are using
export, theWorkeris not an Ecmascript Module that exports that word in a script when theWorkerscript is not set as an Ecmascript Module.