我正在尝试在网络工作人员
constants.js
中使用worker.js
,但它失败并出现以下错误:importScripts
Uncaught SyntaxError: Failed to execute 'importScripts' on 'WorkerGlobalScope':
The URL 'constants.js' is invalid.
和
constants.js
都出现在同一条路径上。我尝试过使用worker.js
,但仍然失败。这就是人为示例的样子:
常量.js
importScripts('./constants.js')
export const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"];
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));
}
}
我需要在许多其他文件中使用常量,这就是为什么将它们维护在一个地方很重要。请推荐。
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;
施工期间将
type
设置为"module"
。