Web Worker 导入在已部署的 React 18 / CRA 上失败

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

我使用网络工作者来加密我的 create-react-app 中的大文件。 在我的 crypto.worker.js 文件中,我像这样导入 CryptoJS..

import * as CryptoJS from "crypto-js";

// eslint-disable-next-line no-restricted-globals
self.onmessage = async function (e) {
    const workerResult = await encryptFile(e.data.file, e.data.key);
    self.postMessage({result: workerResult, keyName: e.data.keyName}); // eslint-disable-line no-restricted-globals
}; ...

然后在我的 React 组件中,我像这样导入并使用这个 webworker:

const webworker = React.useMemo(() => new Worker(new URL('../WebWorkers/encryption.worker.js', import.meta.url)), []);

这在开发中运行我的应用程序时有效,但是当部署应用程序时,我收到以下错误: enter image description here

具体:

Refused to execute script from 'https://DOMAIN+OF+THE+APP/publisher/static/js/static/js/541.fda53aa0.chunk.js' because its MIME type ('text/html') is not executable.

来自 Chrome 的源地图,以防有帮助: enter image description here

我做错了什么吗?请指教..

--- 更新--- 问题是由

形成的url
new URL('../WebWorkers/encryption.worker.js', import.meta.url) 

https://DOMAIN+OF+THE+APP/publisher/static/js/static/js/541.fda53aa0.chunk.js
问题就出在这里
.../static/js/static/js/...
。但是,我仍然不知道如何解决这个问题。

reactjs web-worker webpack-5 mixed-content
1个回答
0
投票

当源加载失败时,不要查看源映射。别忘了这只是一张地图。这个错误让问题很清楚:

because its MIME type ('text/html') is not executable

网址错误。由于导入是由 webpack 完成的,我认为发生这种情况是因为项目内的路径没有修补从服务器看到的路径结构。

既然你无论如何都在使用 webpack,为什么不直接将加密打包到工作代码中呢?这是为了节省资源并允许该组件共享缓存吗?

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