在Electron Vue项目中引入mongoose出现加载器错误求助
Vue CLI + electron-builder 引入mongoose触发加载器错误的解决方案
问题场景
在Vue CLI(v5.0.8)集成electron-builder(v13)的项目中,在background.js里引入mongoose时,触发webpack加载器错误,核心报错为bson.mjs中无法在async函数外使用await关键字。
复现步骤
# Vue CLI版本5.0.8 vue create my-project (选择Vue3、babel、sass、vuex、router,无history模式) cd my-project vue add electron-builder (v13版本) yarn add mongoose
在src/background.js中添加:
const mongoose = require('mongoose')
Node版本:16.20.2
错误信息
error in ./node_modules/bson/lib/bson.mjs Module parse failed: Cannot use keyword 'await' outside an async function (131:26) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); | } > const nodejsRandomBytes = await (async () => { | try { | return (await import('crypto')).randomBytes; @ ./node_modules/mongoose/lib/types/objectid.js 13:17-32 @ ./node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js @ ./node_modules/mongoose/lib/drivers/node-mongodb-native/index.js @ ./node_modules/mongoose/lib/index.js @ ./node_modules/mongoose/index.js @ ./src/background.js @ multi ./src/background.js
解决方法
- 升级Electron版本:确保Electron版本与mongoose依赖的Node.js语法特性兼容
- 配置electronBuilder.externals:在项目根目录的
vue.config.js中添加如下配置,将mongoose排除在webpack打包范围外,直接使用Electron内置的Node.js环境加载该模块:
module.exports = { pluginOptions: { electronBuilder: { externals: ['mongoose'] } } }
原理:webpack默认会打包所有依赖模块,但mongoose及其依赖的bson模块依赖Node.js原生环境特性,将其加入externals后,webpack会跳过对该模块的语法解析与打包,直接在Electron的Node环境中加载原生模块,从而避免语法解析错误。
内容的提问来源于stack exchange,提问作者K.G
相关产品推荐
相关产品推荐

