【发布时间】:2021-07-04 12:00:36
【问题描述】:
我的项目结构是这样的:
moduleA -> 我使用 Rollup 发布到 npm 的库
projectA -> 我的 gatsby 项目,它安装并使用了 moduleA。
我正在使用这个库将我的工作人员与我的其他库代码捆绑到 dist 文件夹中:https://github.com/darionco/rollup-plugin-web-worker-loader
模块A代码:
workers/index.js
let webWorker = null;
if (typeof window !== "undefined") {
webWorker = new Worker(new URL("./my.worker.js", import.meta.url), {
type: "module",
});
}
export default webWorker;
workers/my.worker.js
self.onmessage = (message) => {
console.log("hii");
self.postMessage("yes");
};
当我构建上述库时,结果是这样的:
所以你可以看到工作人员现在正确地在图书馆的 dist 中。这一切都很好。
如果我们查看index.modern.module.js,您会看到这是工作代码的输出:
if (typeof window !== "undefined") {
webWorker = new Worker(new URL("my.worker-f73c7cd4.js", import.meta.url), {
type: "module"
});
}
现在在我的主项目中,我有这个 webpack 规则可以将 import.meta.url 转换为路径,否则 webpack 会崩溃,因为它无法识别 import.meta.url:
config.module.rules.push({
test: /\.jsx?$/,
loader: require.resolve("@open-wc/webpack-import-meta-loader"),
});
我现在运行我的主要 react 项目(内置于 gatsby 和 webpack),这是index.modern.module.js 中的输出:
if (typeof window !== "undefined") {
webWorker = new Worker(new URL("my.worker-8e6a623b.js", ({ url: getAbsoluteUrl('node_modules/@tracktak/dcf-react/dist/index.modern.module.js') }).url), {
type: "module"
});
}
这是网络请求,您可以看到它借入,但我很确定路径是错误的。它只是说 200 好的,因为我认为它会进入 404 页面:
它给了我一个控制台错误:
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
所以,我的问题是。如何将 Web Worker 加载到我的 Gatsby 项目 (projectA) 的公用文件夹中。我需要在这里使用worker-loader 之类的东西吗?我只是不确定它如何在这里工作,因为它在我的 npm 模块中,而不是在我的项目中。
任何帮助都会很棒,我会奖励赏金!
谢谢
编辑:似乎worker-plugin 越来越接近解决方案。如果我在我的主项目中使用它并将 dist 输出中的网络工作者从这个:new URL("my.worker-8e6a623b.js", ({ url: getAbsoluteUrl('node_modules/@tracktak/dcf-react/dist/index.modern.module.js') }).url) 修改为这个:new URL("my.worker-8e6a623b.js") 它工作正常,因为 worker-plugin 只接受字符串参数。
但这不是一个可持续的解决方案,因为显然我不想修改 dist 文件。
【问题讨论】:
-
网络标签的“预览”显示了什么?是代码吗?
-
@DanLevy 它说:“加载响应数据失败”。这意味着它很可能根本不加载工作脚本,而是加载我认为的 html 网页。所以我在工人构造函数中的路径似乎是错误的。我对你的回答有疑问
-
您是否愿意使用简单的解决方案而不是您的插件?
-
@JRichardsz 绝对是。我愿意接受简单的解决方案。即使它不能完全解决它也会很棒,因为我对此很迷茫。
标签: javascript node.js npm webpack web-worker