如何在NextJS+Module Federation远程组件中正确加载图片
解决Next.js Module Federation远程组件图片路径404问题
核心方案:配置远程应用的assetPrefix
Next.js提供的assetPrefix配置项,可全局为静态资源添加基础URL前缀,无需逐个修改图片路径。
1. 远程应用(app001)的next.config.js修改
在原有配置基础上添加assetPrefix:
/** @type {import('next').NextConfig} */ const NextFederationPlugin = require('@module-federation/nextjs-mf'); const nextConfig = { reactStrictMode: true, // 添加远程应用的基础URL前缀 assetPrefix: 'http://localhost:3001', webpack: (config, options) => { config.plugins.push( new NextFederationPlugin({ name: 'app001', filename: 'static/chunks/remoteEntry.js', exposes: { './component': './src/component/index.tsx' }, extraOptions: { enableImageLoaderFix: true, enableUrlLoaderFix: true, automaticAsyncBoundary: true } }), ); return config; } } module.exports = nextConfig
配置后,远程组件中<img src="/01.png" />会自动解析为http://localhost:3001/01.png,无论在哪个宿主应用中渲染,都会指向远程应用的静态资源。
2. 用环境变量实现多环境适配
如果需要区分开发/生产环境,可通过环境变量配置:
- 在远程应用根目录创建
.env文件:
NEXT_PUBLIC_ASSET_PREFIX=http://localhost:3001
- 修改next.config.js:
assetPrefix: process.env.NEXT_PUBLIC_ASSET_PREFIX,
生产环境只需替换环境变量的值为远程应用的生产域名即可。
3. 封装统一图片组件(适合存量项目)
如果已经有大量远程组件,可封装一个通用图片组件统一处理路径:
// src/components/RemoteImage.tsx import React from 'react'; interface RemoteImageProps { src: string; [key: string]: any; } const RemoteImage: React.FC<RemoteImageProps> = ({ src, ...props }) => { const baseUrl = process.env.NEXT_PUBLIC_ASSET_PREFIX; return <img src={`${baseUrl}${src}`} {...props} />; }; export default RemoteImage;
之后所有远程组件中用<RemoteImage src="/01.png" />替代原生<img>,只需维护NEXT_PUBLIC_ASSET_PREFIX一个配置即可。
注意事项
- 确保远程应用的CORS配置允许宿主域名访问静态资源,避免跨域错误;
assetPrefix是Next.js官方针对静态资源路径的配置,比publicUrl更适合当前场景,这也是你之前配置publicUrl无效的原因。
内容的提问来源于stack exchange,提问作者rddd
相关产品推荐
相关产品推荐

