未捕获的语法错误:无法在“WorkerGlobalScope”上执行“importScripts”:URL“constants.js”无效

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

我正在尝试在网络工作人员

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

worker.js

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

Seesaw.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)); } }

我需要在许多其他文件中使用常量,这就是为什么将它们维护在一个地方很重要。请推荐。

javascript reactjs web-worker
1个回答
0
投票
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"
    

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