You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

解决方法

  1. 升级Electron版本:确保Electron版本与mongoose依赖的Node.js语法特性兼容
  2. 配置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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:45:06