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

