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

Expo Web集成bson包报错await未定义,求配置解决方案

解决Expo Web中使用bson包出现Uncaught ReferenceError: await is not defined的问题

问题原因

React Native模块导入技术说明:
我们package.json中的"exports"定义会导致React Native项目导入BSON的CommonJS包而非ES模块包。必须导入CommonJS包,因为BSON的ES模块包使用了顶层await,而React Native的Hermes运行时不支持该语法。

解决方案

  • 方案一:强制Metro为Web环境导入CommonJS版本
    在Expo项目根目录创建或修改metro.config.js,添加配置让Metro在Web构建时优先解析bson的CommonJS入口:
const { getDefaultConfig } = require('expo/metro-config');

const config = getDefaultConfig(__dirname);

config.resolver.resolveRequest = (context, moduleName, platform) => {
  if (moduleName === 'bson' && platform === 'web') {
    return {
      filePath: require.resolve('bson/dist/bson.cjs'),
      type: 'sourceFile',
    };
  }
  return context.resolveRequest(context, moduleName, platform);
};

module.exports = config;
  • 方案二:使用兼容的bson版本
    降级到未在ES模块中使用顶层await的版本,比如bson@4.7.2:
npm install bson@4.7.2
# 或用yarn
yarn add bson@4.7.2
  • 方案三:通过Babel别名指定导入版本
    在babel.config.js中添加别名配置,区分Web和Native环境的bson导入:
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'module-resolver',
        {
          alias: {
            'bson': process.env.EXPO_PLATFORM === 'web' ? 'bson/dist/bson.cjs' : 'bson',
          },
        },
      ],
    ],
  };
};

先安装依赖:

npm install babel-plugin-module-resolver --save-dev

内容的提问来源于stack exchange,提问作者Hesam Zakeri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:49:54