nextjs config_error ai_generated true

错误:`next/image` 上的 src 属性无效,src 必须是字符串且不能是相对路径。

Error: Invalid src prop on `next/image`, src must be a string and cannot be a relative path.

ID: nextjs/invalid-image-src-relative-path

其他格式: JSON · Markdown 中文 · English
95%修复率
90%置信度
1证据数
2023-09-01首次发现

版本兼容性

版本状态引入弃用备注
Next.js 13.0 active
Next.js 14.0 active
Next.js 14.2 active
Next.js 15.0 active

根因分析

`next/image` 组件上的 `src` 属性是相对路径(例如 './image.png' 或 '../assets/img.jpg'),而不是绝对 URL 或静态导入。Next.js 要求对于远程图像使用绝对 URL,对于本地图像使用静态导入。

English

The `src` prop on the `next/image` component is a relative path (e.g., './image.png' or '../assets/img.jpg') instead of an absolute URL or a static import. Next.js requires either an absolute URL (for remote images) or a static import (for local images).

generic

官方文档

https://nextjs.org/docs/app/api-reference/components/image

解决方案

  1. 对本地图像使用静态导入:import logo from './logo.png' 并将其作为 src 传递。
  2. 对远程图像使用绝对 URL。确保主机名在 next.config.js 的 images.remotePatterns 下配置。
  3. 将图像放在 'public' 目录中(例如 'public/images/logo.png'),并使用来自根目录的绝对路径引用:'/images/logo.png'。这是因为公共文件作为静态资源提供。

无效尝试

常见但无效的做法:

  1. 80% 失败

    A leading slash is still a relative path from the domain root, not an absolute URL. Next.js does not treat it as a valid local image path unless it is a static import.

  2. 70% 失败

    Data URLs are strings but are not supported by `next/image` for optimization. The error may change to 'Invalid src prop' or 'Image optimization failed'.

  3. 60% 失败

    The loader prop customizes the image URL generation but does not change the requirement that src must be an absolute URL or static import. The validation still fails.