2 回答
TA贡献1850条经验 获得超11个赞
正如您在问题中所述以及软件包上的这个Github问题所指出的那样,问题nedb的根本原因是webpack的文件解析过程会读取package.browser密钥,以便在target构建为browser或其他值时将特定文件路径别名到另一个位置使它检查package.browser财产。
electron-vue似乎通过将所有NPM依赖项视作避开了webpack捆绑问题,externals这样它们就不会被拉入应用程序捆绑包,而是期望global通过其他某种方式进行定义。您可以类似地nedb在webpack配置中将其指定为外部,然后通过脚本标签或以global其他方式定义对它的引用,将Node版本拉入您的应用程序。
另一个解决方案是创建一个webpack解析器插件,以覆盖问题的要求"./lib/customUtils.js"和"./lib/storage.js"解决方式,从而绕过检查package.browser的那些文件路径别名的解决步骤。
有关如何在Webpack配置中传递自定义解析器插件的信息,请参阅webpack文档。有关如何定义插件以及它们如何工作的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]
}
}
TA贡献1780条经验 获得超4个赞
您无需在渲染器进程上运行数据库,而是可以在主进程上运行其他想要的数据库,例如sql,sqlite,mongodb等。
如果您不介意切换数据库,可以通过以下方法实现此目的。在Electron中存在一个名为ipcMain和ipcRenderer的类,该类用于使渲染器进程和主进程通信。您可以使用ipc发送/接收任何类型的数据。
这是一个例子:
Renderer.js
const btnSave = document.getElementById('btn-save')
// Get any data from forms, etc
btn.addEventListener('click', () => {
// ipcRender sends the data via 'receive-data-to-save-in-database' channel, you
// you can send any type of data, and have has many args you want. In this case I
// sent a a empty object
ipcRenderer.send('receive-data-to-save-in-database', {})
})
Main.js
// ipcMain listens to channel 'receive-data-to-save-in-database'
ipcMain.on('receive-data-to-save-in-database', (event, args) => {
// Code to save in database
// The empty object will be received in args parameter
})
这不是您想要的,而是一种解决方法。
添加回答
举报
