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

Expo项目Jest测试报错:Firebase导入出现模块外import语句错误

解决Expo项目中Firebase + Jest测试的模块语法错误

问题核心

在Expo项目中使用Firebase v9,运行Jest测试时触发SyntaxError: Cannot use import statement outside a module,且仅在Firebase相关导入代码中出现。尝试添加"type": "module"到package.json后出现Babel异步配置错误,修改babel.config.js为.cjs后缀又回到原问题,改用require导入也无效。

解决方案

1. 调整Jest转译忽略规则

Firebase v9默认采用ESM模块语法,而Jest默认不会转译node_modules中的包,导致语法报错。需要将Firebase相关包加入Jest的转译白名单:

修改package.json中的jest配置,在transformIgnorePatterns的例外列表中添加firebase|@firebase:

"jest": {
  "preset": "jest-expo",
  "transformIgnorePatterns": [
    "node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg|firebase|@firebase)"
  ]
}

2. 移除"type": "module"配置

Expo项目默认基于CommonJS配置,添加"type": "module"会与Jest的同步Babel处理逻辑冲突,直接删除package.json中的该字段即可。

3. 对齐Jest与Jest-Expo版本

当前你的jest(26.6.3)和jest-expo(48.0.1)版本不匹配(Expo 47对应jest-expo 47.x),版本不一致会引发兼容性问题:

更新package.json中的依赖版本:

"dependencies": {
  // ... 其他依赖保持不变
  "jest": "^27.5.1",
  "jest-expo": "^47.0.1"
}

执行依赖安装命令:

npm install
# 或
yarn install

4. 保持Babel配置不变

继续使用原有的babel.config.js(CommonJS格式),无需修改为.cjs后缀:

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
  };
};

验证

完成上述修改后,重新运行测试命令:

npm test

此时Jest会正确转译Firebase的ESM代码,解决模块语法错误。

内容的提问来源于stack exchange,提问作者King In The North

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:35:00