Next.js本地图片组件yarn dev正常但yarn build报错求助
问题场景
用Next.js搭建CS作品集网页,编写了展示圆形头像的CircularImage组件,yarn dev时图片正常显示,但执行yarn build时出现以下编译错误:
Failed to compile.
./src/components/CircularImage/mememe.jpeg
TypeError: Failed to parse URL from /Users/jasminewang/Documents/FALL 2023/mPortfolio-main/node_modules/next/dist/server/lib/squoosh/mozjpeg/mozjpeg_node_dec.wasm
at Object.fetch (node:internal/deps/undici/undici:14152:11)Import trace for requested module:
./src/components/CircularImage/index.tsx
./src/components/Header/index.tsx
./src/components/Layout.tsx
./src/pages/index.tsxBuild failed because of webpack errors
error Command failed with exit code 1.
组件代码如下:
import React from "react"; import Image from "next/dist/client/image"; import image from "./mememe.jpeg"; const CircularImage = () => { return ( <div style={{ width: "100px", height: "100px", borderRadius: "50%", overflow: "hidden", }} > <Image src={image} alt="A pic of me" /> </div> ); }; export default CircularImage;
解决方案
1. 修正Image组件导入路径
直接导入Next.js内部的next/dist/client/image属于非公开API调用,dev环境兼容但build时会触发依赖解析错误,改为官方推荐的导入方式:
// 替换原导入行 import Image from 'next/image';
2. 禁用图片优化(临时修复)
若导入修正后仍报错,大概率是Next.js内置的squoosh图片优化工具出现依赖问题,可在配置中禁用图片优化:
- 修改
next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { images: { unoptimized: true, }, }; module.exports = nextConfig;
- 或直接在Image组件添加属性(Next.js 13+支持):
<Image src={image} alt="A pic of me" unoptimized />
3. 将图片移至public目录
把mememe.jpeg放到项目根目录的public文件夹下,直接用路径引用(无需import),同时指定图片尺寸:
import React from "react"; import Image from "next/image"; const CircularImage = () => { return ( <div style={{ width: "100px", height: "100px", borderRadius: "50%", overflow: "hidden", }} > <Image src="/mememe.jpeg" alt="A pic of me" width={100} height={100} /> </div> ); }; export default CircularImage;
4. 升级Next.js版本
部分旧版本Next.js存在squoosh依赖bug,尝试升级到最新稳定版:
yarn add next@latest
内容的提问来源于stack exchange,提问作者Jasmine

