Macbook M1运行React Native时metro无法解析assets模块报错
问题场景:Macbook M1 环境 React Native 项目 SVG 导入偶发无法解析问题
现有 metro.config.js 配置
const {getDefaultConfig} = require("metro-config") module.exports = (async () => { const { resolver: {sourceExts, assetExts}, } = await getDefaultConfig() return { transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: true, }, }), babelTransformerPath: require.resolve("react-native-svg-transformer"), }, resolver: { assetExts: assetExts.filter(ext => ext !== "svg"), sourceExts: [...sourceExts, "svg"], }, } })()
项目目录结构
Root |--app |--assets | |--icons | |--components |--tab |-tab.tsx
导入写法
tab.tsx 中使用绝对路径导入SVG:
import CloseIcon from "assets/icons/close-icon.svg"
报错信息
error: Error: Unable to resolve module assets/icons/close-icon.svg from root/app/components/tab/navigation/tab.tsx: assets/icons/close-icon.svg could not be found within the project or in these directories:
node_modules
../../node_modules
已尝试操作
- 执行过常规 Metro 缓存清除操作,操作参考截图:

- 常规清缓存操作无效,仅关闭所有应用重启电脑后报错会暂时消失,运行一段时间后会复现。
解决方案
该问题由路径映射配置缺失叠加M1架构下Metro缓存的特殊机制共同导致,按以下步骤操作可彻底修复:
- 补全Metro路径解析配置
当前使用的assets/开头的绝对路径导入没有配置对应解析规则,Metro默认只会从node_modules、当前文件相对路径查找依赖,重启电脑偶然生效只是冷启动时碰巧命中了临时文件树缓存,属于非稳定逻辑。
修改metro.config.js,显式指定监听目录和路径映射规则:
const {getDefaultConfig} = require("metro-config") const path = require('path') module.exports = (async () => { const { resolver: {sourceExts, assetExts}, } = await getDefaultConfig() return { // 显式声明需要监听的项目业务目录 watchFolders: [path.resolve(__dirname, 'app')], transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: true, }, }), babelTransformerPath: require.resolve("react-native-svg-transformer"), }, resolver: { assetExts: assetExts.filter(ext => ext !== "svg"), sourceExts: [...sourceExts, "svg"], nodeModulesPaths: [path.resolve(__dirname, 'node_modules')], // 自定义路径解析规则,映射assets开头的导入到app目录下 resolveRequest: (context, moduleName, platform) => { if (moduleName.startsWith('assets/')) { return context.resolveRequest( context, path.resolve(__dirname, 'app', moduleName), platform ) } return context.resolveRequest(context, moduleName, platform) } }, } })()
- 补全TypeScript路径配置(使用TS的项目需要配置)
在项目根目录tsconfig.json中添加路径映射,避免编辑器提示报错同时兼容Metro解析逻辑:
{ "compilerOptions": { "baseUrl": "./", "paths": { "assets/*": ["app/assets/*"] } } }
- 执行全量缓存清除
M1架构下Metro缓存会存放在系统级临时目录,普通--reset-cache参数无法完全清理,依次执行以下命令:
# 关闭所有Metro、Node相关进程 pkill -f metro pkill -f node # 清除系统级Metro缓存 rm -rf $TMPDIR/metro-* rm -rf $TMPDIR/haste-* # 清除项目本地缓存 rm -rf node_modules/.cache # 启动时强制重置缓存 # iOS项目执行 npx react-native run-ios --reset-cache # Android项目执行 npx react-native run-android --reset-cache
- 版本兼容性校验
确认安装的react-native-svg-transformer版本与项目内react-native-svg版本匹配,M1环境下版本不兼容也会导致SVG解析偶发失效,安装时不要加--force参数强制忽略版本冲突。
配置完成后无需重启电脑,后续正常启动项目即可,Metro增量更新时也不会再出现路径找不到的问题。
内容的提问来源于stack exchange,提问作者jc28
相关产品推荐
相关产品推荐

