正如您在问题中所述,并且根据 nedb 包上的 Github issue,问题的根本原因是 webpack 的文件解析过程读取了 package.browser 键,以便将特定文件路径别名到不同的位置当target 构建为browser 或其他一些会导致它检查package.browser 属性的值时。
electron-vue 通过将所有 NPM 依赖项视为externals 对sidestep the webpack bundling issue 显示,这样它们就不会被拉入应用程序包,而是通过其他方式在global 上定义。您可以类似地将 nedb 指定为 webpack 配置中的外部,并通过 script 标签或在 global 上定义对它的引用以其他方式将 Node 版本拉入您的应用程序。
另一种解决方案是创建一个 webpack 解析器插件,以覆盖 "./lib/customUtils.js" 和 "./lib/storage.js" 的问题要求如何得到解决,绕过检查 package.browser 以获取这些文件路径的别名的解析步骤。
在你的 Webpack 配置中查看 how to pass a custom resolver plugin 的 webpack 文档。有关how plugins are defined 及其工作原理的更多详细信息,请参阅wepback/enhanced-resolve 文档。
本质上,插件是一个带有apply 方法的对象,它采用resolver 实例并执行文件解析过程的某些步骤。在下面的示例中,我们测试当前正在解析的文件是否在 nedb 包中,以及它是否是两个有问题的浏览器别名之一。如果是这样,我们使用正确的文件路径退出解析过程。否则我们什么也不做,按照正常的解决过程。
// Prevents nedb from substituting browser storage when running from the
// Electron renderer thread.
const fixNedbForElectronRenderer = {
apply(resolver) {
resolver
// Plug in after the description file (package.json) has been
// identified for the import, which makes sure we're not getting
// mixed up with a different package.
.getHook("beforeDescribed-relative")
.tapAsync(
"FixNedbForElectronRenderer",
(request, resolveContext, callback) => {
// When a require/import matches the target files, we
// short-circuit the Webpack resolution process by calling the
// callback with the finalized request object -- meaning that
// the `path` is pointing at the file that should be imported.
const isNedbImport = request.descriptionFileData["name"] === "nedb"
if (isNedbImport && /storage(\.js)?/.test(request.path)) {
const newRequest = Object.assign({}, request, {
path: resolver.join(
request.descriptionFileRoot,
"lib/storage.js"
)
})
callback(null, newRequest)
} else if (
isNedbImport &&
/customUtils(\.js)?/.test(request.path)
) {
const newRequest = Object.assign({}, request, {
path: resolver.join(
request.descriptionFileRoot,
"lib/customUtils.js"
)
})
callback(null, newRequest)
} else {
// Calling `callback` with no parameters proceeds with the
// normal resolution process.
return callback()
}
}
)
}
}
// Register the resolver plugin in the webpack config
const config = {
resolve: {
plugins: [fixNedbForElectronRenderer]
}
}