React Native导入SVG转JSX组件报错:无法解析模块文件不存在
React Native导入JSX SVG组件的模块解析错误修复方案
问题背景
将SVG通过transform.tools转换为JSX组件LetsPlay.jsx后,在同目录的PlayButton.js中导入该组件时,触发无法解析模块:这些文件均不存在错误,已确认导入路径的层级关系正确。
相关代码
PlayButton.js
import React from 'react'; import {TouchableOpacity, Animated} from 'react-native'; import LetsPlay from './LetsPlay'; // 报错位置 const PlayButton = ({navigation}) => { return ( <Animated.View> <TouchableOpacity onPress={() => { navigation.navigate('GameSelection'); }}> <LetsPlay /> </TouchableOpacity> </Animated.View> ); }; export default PlayButton;
LetsPlay.jsx
import * as React from 'react'; import Svg, {Circle, G, Path, Defs} from 'react-native-svg'; /* SVGR has dropped some elements not supported by react-native-svg: filter */ function LetsPlay(props) { return ( <Svg width={114} height={114} viewBox="0 0 114 114" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}> <Circle cx={57} cy={57} r={53.5} fill="#F2D330" stroke="#FCFCFA" strokeWidth={7} /> <G filter="url(#filter0_d_85_425)"> <Path d="M77 52.67c3.333 1.924 3.333 6.736 0 8.66L50.75 76.486c-3.333 1.924-7.5-.482-7.5-4.33V41.844c0-3.85 4.167-6.255 7.5-4.33L77 52.67z" stroke="#FCFCFA" strokeWidth={2.5} shapeRendering="crispEdges" /> </G> <Defs /> </Svg> ); } export default LetsPlay;
环境版本
react-native: 0.68.2react-native-svg: ^13.7.0
修复步骤
1. 显式指定.jsx后缀导入
React Native 0.68版本的Metro默认不会自动解析.jsx后缀的文件,修改导入语句为:
import LetsPlay from './LetsPlay.jsx';
2. 配置Metro支持JSX后缀(可选)
若希望无需每次添加后缀,修改项目根目录的metro.config.js,将jsx加入可解析的文件扩展名列表:
const { getDefaultConfig } = require('@react-native/metro-config'); const config = getDefaultConfig(__dirname); config.resolver.sourceExts = [...config.resolver.sourceExts, 'jsx']; module.exports = config;
修改完成后,重启Metro服务并清除缓存:
npx react-native start --reset-cache
3. 核对文件名大小写
确保本地文件的实际命名(包括大小写)与导入语句完全一致——部分系统(如Linux/Windows)对文件名大小写敏感,若文件名为letsplay.jsx而导入用./LetsPlay,会导致解析失败。
4. 清除项目缓存
执行以下命令彻底清除缓存,解决缓存残留导致的解析异常:
# 清除Metro缓存 npx react-native start --reset-cache # 重置依赖并清除npm缓存 rm -rf node_modules package-lock.json npm install
内容的提问来源于stack exchange,提问作者Shagun Deogharkar
相关产品推荐
相关产品推荐

