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

React Native运行yarn test报错:Cannot use import statement outside a module

解决React Native Jest测试中"Cannot use import statement outside a module"错误

错误根源是react-native-iphone-x-helper依赖未被Jest转译,它使用的ES模块语法(import)在非模块环境下无法被识别,导致报错。

按以下步骤修复:

  • 修改package.json中的Jest配置,将react-native-iphone-x-helper加入transformIgnorePatterns的白名单,让Jest转译该包:
"jest": {
  "preset": "react-native",
  "setupFilesAfterEnv": [
    "@testing-library/jest-native/extend-expect"
  ],
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?@?react-native|react-native-responsive-fontsize|react-navigation|@react-native-community|@react-navigation|react-native-animatable|react-native-iphone-x-helper)"
  ]
}
  • 清除Jest缓存,避免旧配置干扰:
yarn test --clearCache
  • 重新运行测试:
yarn test

transformIgnorePatterns中的(?!...)是负向预查规则,意为除了括号内列出的包,其余node_modules文件均不转译。把出问题的依赖加入白名单后,Jest会处理它的ES模块语法,解决报错。

内容的提问来源于stack exchange,提问作者Madushan Weerathunga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:12:43