问题描述
我正在尝试将我的应用迁移到最新版本的 NextJS (v10)。他们引入了一个新的图像组件(请参阅 Release notes),当我尝试使用它时,我的应用无法正确提供图像。
在我的 next.config.js
中,我设置了一个 basePath
值,以便能够从子路径而不是根路径为我的应用程序提供服务:
const nextConfig = {
pageExtensions: ["js","jsx","ts","tsx","mdx","md"],basePath: "/an",};
设置后,Image
组件无法获取我的 img 文件。没有它一切正常,但我的应用程序无法在 /an
当有一个 src
能够提供图像时,我应该如何定义 basePath
属性?
<Image
src="/me.jpg" <-- This is not working with basePath
alt="A photo of myself."
className="rounded-full h-48 w-48 mx-auto"
width="192"
height="192"
/>
解决方法
此处有 open issue 和 a PR(截至撰写此答案时)。
与此同时,作为一种解决方法,(来自链接的问题)
import React from 'react';
import Image from 'next/image';
const basePath = process.env.NEXT_PUBLIC_BASE_PATH;
const ImageWithBasePath: typeof Image = (props) => {
const url = props.src?.startsWith('/')
? `${basePath || ''}${props.src}`
: props.src;
return <Image {...props} src={url}></Image>;
};
export default ImageWithBasePath;
将您在 env 中的 basePath
导出为 NEXT_PUBLIC_BASE_PATH
并将导入的 Image form 'next/image'
替换为 import ImageWithBasePath from './ImageWithBasePath'
我不知道这是不是问题,但是您必须像这样将 className 提取到父元素
<div className="rounded-full h-48 w-48 mx-auto">
<Image
src="/me.jpg" <-- This is not working with basePath
alt="A photo of myself."
width="192"
height="192"
/>
</div>