执行expo start --web出现大量模块未找到错误与警告求助
执行expo start --web命令时,出现大量模块未找到的错误与警告,示例如下:
ERROR in ./node_modules/react-native/Libraries/Network/XMLHttpRequest.js:19:22 Module not found: Can't resolve './RCTNetworking' WARNING in ./node_modules/react-native/Libraries/WebSocket/WebSocket.js:245:19 export 'default' (imported as 'BlobManager') was not found in '../Blob/BlobManager' (module has no exports) WARNING in ./node_modules/react-native/Libraries/LogBox/UI/LogBoxNotification.js:94:5 export 'default' (imported as 'View') was not found in '../../Components/View/View' (module has no exports)
总计遇到1个错误和145条警告,曾尝试通过手动配置webpack alias修复部分问题,配置代码如下:
const createExpoWebpackConfigAsync = require('@expo/webpack-config'); module.exports = async function (env, argv) { const config = await createExpoWebpackConfigAsync(env, argv) config.resolve.alias['../Utilities/Platform'] = 'react-native-web/dist/exports/Platform' config.resolve.alias['./Platform'] = 'react-native-web/dist/exports/Platform' config.resolve.alias['../Utilities/BackHandler'] = 'react-native-web/dist/exports/BackHandler' config.resolve.alias['../../Image/Image'] = 'react-native-web/dist/exports/Image' config.resolve.alias['../../Utilities/Platform'] = 'react-native-web/dist/exports/Platform' config.resolve.alias["./PlatformColorValueTypes"] = "react-native-web/dist/exports/StyleSheet"; config.resolve.alias["../../StyleSheet/PlatformColorValueTypes"] = "react-native-web/dist/exports/StyleSheet"; config.resolve.alias["./RCTAlertManager"] = "react-native-web/dist/exports/Alert"; config.resolve.alias["./BaseViewConfig"] = "react-native-web/dist/exports/View"; config.resolve.alias['../Components/AccessibilityInfo/legacySendAccessibilityEvent'] = "react-native-web/dist/exports/AccessibilityInfo"; return config };
以下是彻底解决该问题的方案:
修复依赖版本兼容性
运行npx expo install --fix,该命令会自动检查并修复expo、react-native、react-native-web、@expo/webpack-config等核心依赖的版本不匹配问题,确保各库版本互相兼容。移除手动添加的Webpack Alias
@expo/webpack-config已经内置了完整的react-native-web模块映射规则,手动添加的alias可能和默认规则冲突,导致模块解析异常。先删除自定义的alias配置,恢复默认webpack配置后重新测试。过滤不兼容的原生模块
如果项目中引入了仅支持iOS/Android的原生React Native库,需要在webpack配置中排除这些模块,或者替换为Web兼容的替代库。可以在webpack配置中添加如下规则:const createExpoWebpackConfigAsync = require('@expo/webpack-config'); module.exports = async function (env, argv) { const config = await createExpoWebpackConfigAsync(env, argv); // 添加规则过滤非Web兼容模块 config.module.rules.push({ test: /\.js$/, exclude: /node_modules\/(?!(react-native-web|@expo|expo-modules-core)\/).*/, use: { loader: 'babel-loader', options: { presets: ['babel-preset-expo'], }, }, }); return config; };清除缓存后重启项目
执行npx expo start --web --clear,彻底清除项目缓存后重新构建,避免缓存导致的依赖解析错误。避免直接导入React Native内部模块
检查项目代码中是否存在直接导入react-native/Libraries/xxx这类内部模块的情况,这类模块大多没有被react-native-web适配,建议替换为react-native官方导出的公开API,或者使用Web原生API替代。
内容的提问来源于stack exchange,提问作者isaak

