Next.js导出-自定义图像加载程序不工作



我正在尝试构建和导出我的Next.JS项目,并且我在导出时遇到了图像优化错误。

我已经创建了一个自定义加载器,创建了一个文件/services/imageLoader.js,其中包含以下内容:

export default function LocalImageLoader({src, width, quality}) {
var fileName = src.split("/").pop();
return `./_next/static/media/${fileName}`;
}

并且,在我使用next/image组件的所有页面中,我添加了loader属性,指向我的LocalImageLoader函数,如下所示:

import LocalImageLoader from '../services/imageLoader';
import logoImage from '../resources/images/logo.png';
// boring stuff here
<Image loader={LocalImageLoader} src={logoImage} alt="Logo" className="img-fluid" />
// more boring stuff here

之后,每次我尝试运行npm run export(我已经在我的包中设置了导出脚本)。json,运行next build && next export),并在我的屏幕上出现以下错误:

Error: Image Optimization using Next.js' default loader is not compatible with `next export`.
Possible solutions:
- Use `next start` to run a server, which includes the Image Optimization API.
- Use any provider which supports Image Optimization (like Vercel).
- Configure a third-party loader in `next.config.js`.
- Use the `loader` prop for `next/image`.
Read more: https://nextjs.org/docs/messages/export-image-api
at /home/raphael/Projects/Next/learning/testProject/node_modules/next/dist/export/index.js:256:23
at async Span.traceAsyncFn (/home/raphael/Projects/Next/learning/testProject/node_modules/next/dist/trace/trace.js:74:20)

谁能告诉我我做错了什么?谢谢!

您忘记将自定义加载程序添加到next.config.js。您将需要执行如下代码片段所示的操作。如果你不能成功,有可用的加载器,因为默认的加载器在你导出时不能工作。

module.exports = {
images: {
loader: 'custom',
path: 'https://example.com/myaccount/',
},
}

更多信息在这里:https://nextjs.org/docs/api-reference/next/image#loader-configuration

最新更新