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

Next.js MDX中使用Image模糊占位符报错的解决求助

解决Next Image模糊占位符及child_process报错问题

方案一:静态导入图片(最适合新手)

直接通过静态导入方式引入图片,Next.js会自动提取图片的宽高、生成模糊占位符的base64,无需手动配置:

import Image from 'next/image';
// 路径从public文件夹根目录开始
import projectImage from '/public/projects/ellingsen/Imagen 1.webp';

export default function ProjectPage() {
  return (
    <Image
      src={projectImage}
      placeholder="blur"
      alt="Ellingsen project image"
    />
  );
}

方案二:动态加载public图片(手动配置宽高与blurDataURL)

如果必须用/xxx这种public路径加载图片,需要手动提供图片实际宽高和blurDataURL,同时解决child_process报错:

为什么会出现child_process报错?

child_process是Node.js的服务器端模块,客户端组件无法调用。必须在服务器端函数(如getStaticProps/getServerSideProps)或构建时脚本中生成图片的base64。

具体步骤:

  1. 安装图片处理库sharp(用于生成缩略图base64):
npm install sharp
  1. 在页面组件中通过getStaticProps(静态生成)生成blurDataURL:
import Image from 'next/image';

export default function ProjectPage({ blurDataURL, imageWidth, imageHeight }) {
  return (
    <Image
      src="/projects/ellingsen/Imagen%201.webp"
      placeholder="blur"
      blurDataURL={blurDataURL}
      width={imageWidth}
      height={imageHeight}
      alt="Ellingsen project image"
    />
  );
}

// 仅在服务器端执行的函数,可安全使用Node.js模块
export async function getStaticProps() {
  const fs = require('fs');
  const path = require('path');
  const sharp = require('sharp');

  // 拼接public目录下的图片绝对路径
  const imageAbsolutePath = path.join(process.cwd(), 'public', 'projects', 'ellingsen', 'Imagen 1.webp');
  
  // 生成小尺寸缩略图并转为base64
  const imageBuffer = await sharp(imageAbsolutePath)
    .resize(20, 20) // 生成20x20的极小缩略图,保证模糊效果同时体积小
    .webp()
    .toBuffer();
  const blurDataURL = `data:image/webp;base64,${imageBuffer.toString('base64')}`;

  // 通过sharp自动获取图片实际宽高
  const imageMetadata = await sharp(imageAbsolutePath).metadata();
  const imageWidth = imageMetadata.width;
  const imageHeight = imageMetadata.height;

  return {
    props: {
      blurDataURL,
      imageWidth,
      imageHeight,
    },
    // 可选:设置重新生成时间,适合图片更新场景
    revalidate: 86400,
  };
}

备选方案:放弃模糊占位符

如果暂时不想处理配置,可直接移除placeholder="blur"属性,或改为placeholder="empty"实现空白占位:

<Image
  src="/projects/ellingsen/Imagen%201.webp"
  placeholder="empty"
  width={1920} // 需手动填写实际宽高
  height={1080}
  alt="Ellingsen project image"
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:02:41