You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js无法识别本地图片路径?求助排查问题

Next.js Hero组件本地图片无法识别的问题

刚接触Next.js,跟着《How To Make a Hero Image in Next.js》教程制作Hero组件时,遇到本地图片路径无法识别的问题,按教程操作仍报错。

控制台错误信息

error - ./components/Hero/Hero.tsx:1:0
Module not found: Can't resolve '../../public/RobotHeroImage.jpeg'
> 1 | import heroImage from '../../public/heroImage.jpeg';
  2 | import Image from 'next/image';
  3 | import styles from '../../styles/Styles.module.css';

Hero组件代码

import Image from 'next/image';
import styles from '../../styles/Styles.module.css';
import heroImage from '../../public/heroImage.jpeg';

const { heroContent, heroWrapper, imageWrapper } = styles;
    
const Hero = () => {
  return (
    <div>
      <div className={heroWrapper}>
        <div className={imageWrapper}>
          <Image priority src={IMAGE_URL} layout="fill" objectFit="cover" objectPosition="center" alt="hero image example" />
        </div>

        <div className={heroContent}>
          <h1>Hero Image</h1>
          <p>Next.js hero image example.</p>
        </div>
      </div>
    </div>
  );
};

export default Hero;

样式文件styles.css代码

.heroWrapper {
  position: relative;
  width: 100vw;
  height: 50vh;
}

.imageWrapper {
  z-index: -1;
}

.heroContent {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

问题排查与解决

  • 文件名/路径不匹配:控制台提示找不到RobotHeroImage.jpeg,但你导入的是heroImage.jpeg,检查public目录下的图片文件名是否完全一致(注意大小写、后缀名,比如.jpeg和.jpg是不同文件),确保没有拼写错误。
  • 引用变量错误:你导入了heroImage,但<Image>组件里用的是未定义的IMAGE_URL,需改为src={heroImage}。
  • 布局配置缺失:使用layout="fill"时,父容器.imageWrapper必须设置定位和宽高,否则图片无法渲染。修改样式:
    .imageWrapper {
      z-index: -1;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    
  • 路径验证:确认../../public/heroImage.jpeg路径是否符合你的项目目录结构,比如Hero组件在components/Hero/Hero.tsx,public在项目根目录的话路径是正确的,若目录结构有调整需同步修改导入路径。

内容的提问来源于stack exchange,提问作者Waiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:45:27