gpt4 book ai didi

Webpack:使用 node 的 require.resolve() 而不是 webpack 的

转载 作者:行者123 更新时间:2023-12-03 12:22:28 25 4
gpt4 key购买 nike

我有一个使用ceratin nodejs lib(@grpc/proto-loader)的 Electron 项目。
生产构建不起作用,因为 webpack 替换了 要求.resolve() 具有自己的函数,该函数返回模块 ID 而不是路径。如何防止 webpack 这样做?

我试图将有问题的包添加到“外部”,但这似乎不起作用。

我希望应用程序使用节点的 require() 函数。
我知道可以使用 non_webpack_require,但我不能修改包的代码,它是第 3 方库。那么有没有更好的方法呢?

最佳答案

我写了一个 hack 来解决这个问题:https://github.com/grpc/grpc-node/issues/969#issuecomment-633271735

更新您的 webpack.config.js拥有一个新的加载器(首先指定它):

...
rules: [
{
test: /@grpc\/proto-loader/,
use: path.resolve('scripts/remove-proto-loader-protos.js'),
},
...

然后创建文件 scripts/remove-proto-loader-protos.js使用以下代码:

// https://github.com/grpc/grpc-node/issues/969
module.exports = function (source) {
if (source.includes(`Load Google's well-known proto files`)) {
return source.replace(/\/\/ Load Google's well-known proto files.*?\n}/gis, '')
} else {
return source
}
}

就是这样!原型(prototype)加载代码将被自动清除。无需单独的 fork 并手动更新它们。

这当然意味着如果有人需要这些 proto 文件,您必须手动加载它们。此外,如果谷歌更新了他们的代码,这个黑客可能需要在 future 更新。我知道,这是一个 hack,但你能做什么? ¯\_(ツ)_/¯

关于Webpack:使用 node 的 require.resolve() 而不是 webpack 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com