使用下一版本12.3.2。
我的 NextJS 应用程序中有一个自定义组件 ImagewithFallback 设置。由于某种原因,它不是将图像加载为 webp,而是加载为 jpg。我尝试删除自定义加载程序,因为默认加载程序使用下一个图像优化 api,但随后出现 500 服务器错误。这些图像来自我在另一个端口上运行的 mongodb 数据库。在 vercel 上,它们是从 api 发送的。下面是我的整个自定义图像组件。
import React, { useEffect, useState } from "react";
import Image from "next/image";
import PropTypes from "prop-types";
const ImageWithFallback = (props) => {
const { src, fallbackSrc, width, height, objectFit, presrc, ...rest } = props;
const [imgSrc, setImgSrc] = useState(src);
// update the image src if a new src is supplied. e.g. first src is undefined but then later its defined
// without this the fallback image will always be selected if the initial component render has a bad src
useEffect(() => {
if (!src || src.endsWith("null") || src.endsWith("undefined")) {
setImgSrc(fallbackSrc);
} else if (src !== imgSrc) {
setImgSrc(src);
}
}, [src]);
const loader = ({ src, width, quality }) => {
return `${src}?w=${width}&q=${quality || 75}`;
};
return (
<Image
{...rest}
width={width}
height={height}
src={imgSrc}
objectFit={objectFit}
onError={() => {
setImgSrc(fallbackSrc);
}}
/>
);
};
ImageWithFallback.propTypes = {
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
src: PropTypes.string,
fallbackSrc: PropTypes.string,
objectFit: PropTypes.string,
};
ImageWithFallback.defaultProps = {
fallbackSrc: "/images/placeholder.gif",
};
export default ImageWithFallback;
对于我的 next.config.js,我已经为 localhost 设置了域名
images: {
domains: ['localhost'],
},
如何才能将从本地数据库服务器发送的图像转换为 webp?
您应该使用以下配置
images: {
domains: ['http://localhost:3000'],
},
这是因为您添加了 unoptimized: true 到 next.config 文件