Expo/React Native 结合 Next.js 图片无法显示问题排查
解决Native Base Solito模板中Next.js图片无法显示的问题
核心问题分析
你当前的配置存在两个关键问题:
next-images与 Webpack5、Native Base 适配器存在兼容性冲突,Expo + Next.js 现在无需单独依赖next-images,官方适配器已整合图片处理逻辑- Monorepo 结构下的路径解析配置不全,导致图片资源无法被正确识别
修正后的 next.config.js 配置
替换你现有的配置为以下内容:
const { withNativebase } = require('@native-base/next-adapter'); const { withExpo } = require('@expo/next-adapter'); const withFonts = require('next-fonts'); const withPlugins = require('next-compose-plugins'); module.exports = withPlugins( [withFonts, [withExpo, { projectRoot: __dirname }], withNativebase], { reactStrictMode: true, webpack5: true, webpack: (config, options) => { // 适配 monorepo 路径别名,简化导入 config.resolve.alias = { ...config.resolve.alias, 'react-native$': 'react-native-web', '@expo/vector-icons': 'react-native-vector-icons', 'app': require('path').resolve(__dirname, './packages/app'), }; config.resolve.extensions = [ '.web.js', '.web.ts', '.web.tsx', ...config.resolve.extensions, ]; // 确保图片 loader 正确处理 monorepo 中的资源 config.module.rules.push({ test: /\.(png|jpe?g|gif|svg)$/i, use: [ { loader: 'file-loader', options: { publicPath: '/_next', name: 'static/media/[name].[hash].[ext]', }, }, ], }); return config; }, } );
图片使用的正确方式
- 导入方式:利用别名简化导入(上面配置了
app别名),或者确保相对路径正确:
// 用别名导入(推荐) import GrayBox from 'app/resources/images/graybox.png'; // 相对路径导入 import Car from '../../../../packages/app/resources/images/car.png';
- 组件使用:优先用 Solito 提供的跨端统一
Image组件(模板自带),也可针对Web/Native分别适配:
// 跨端统一使用 Solito Image(推荐) import { Image } from 'solito/image'; <Image source={{ uri: GrayBox }} // 注意需要包裹成uri对象 style={{ width: 500, height: 750 }} alt="test" /> // Web端单独使用Next.js Image组件 import NextImage from 'next/image'; <NextImage src={GrayBox} width={500} height={750} alt="test" />
为什么之前的配置会报错?
你补充的 plugins 配置逻辑错误,withNativebase 需要和 withExpo 链式调用,而非放在 plugins 数组中;重复加载 withImages 会和 Webpack5 自带的图片处理逻辑冲突,导致文件类型识别失败的报错。
额外注意事项
- 确认图片资源路径正确,确保
packages/app下的资源能被 Next.js 编译捕获 - 清理Next.js缓存:执行
rm -rf .next && npm run dev,避免旧配置缓存残留
内容的提问来源于stack exchange,提问作者Steven Matthews
相关产品推荐
相关产品推荐

