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
相关产品推荐
相关产品推荐

