WebDriverIO+Jasmine+TS引入react-native报Cannot use import outside module错误
问题根因
你遇到的Cannot use import statement outside a module报错,本质是@babel/register默认不会转译node_modules目录下的第三方包代码,你引入的react-native包本身采用ES Module语法编写,Node.js默认的CommonJS模块加载器无法直接解析,因此抛出语法错误。
解决方案
按以下步骤调整配置即可解决:
1. 修改babel.config.js配置
放开对react-native包的转译限制,明确输出CommonJS格式代码:
module.exports = { presets: [ ['@babel/preset-env', { targets: { node: 'current' }, modules: 'commonjs' }] ], // 仅对react-native相关代码做转译,其余node_modules包保持忽略减少编译耗时 ignore: [ (filename) => { return /node_modules/.test(filename) && !/node_modules\/react-native/.test(filename) } ] };
2. 调整wdio.conf.js钩子配置
修正注册顺序,避免ts-node和babel转译逻辑冲突,同时给@babel/register传入统一的转译规则:
beforeSession: function (config, capabilities, specs) { require('@babel/register')({ extensions: ['.js', '.jsx', '.ts', '.tsx'], ignore: [ (filename) => { return /node_modules/.test(filename) && !/node_modules\/react-native/.test(filename) } ] }); }, before: function () { // 先完成babel注册再初始化ts-node require('ts-node').register({ files: true }); browser.maximizeWindow(); },
同时删除jasmineNodeOpts中的requires: ['@babel/register']配置,避免重复注册。
3. 补充tsconfig.json配置
在compilerOptions字段中添加以下配置,避免TypeScript输出ES模块语法产生冲突:
"module": "CommonJS", "moduleResolution": "node", "allowJs": true
兜底优化方案
如果只是需要判断当前运行平台,完全可以直接通过WebDriverIO提供的能力参数判断,不需要引入react-native的Platform依赖,从根源避免依赖冲突:
const currentPlatform = browser.capabilities.platformName.toLowerCase(); const isWin32 = currentPlatform.includes('win'); const isMacOS = currentPlatform.includes('mac');
内容的提问来源于stack exchange,提问作者lakers5824
相关产品推荐
相关产品推荐

