我使用Next.jsImage
组件进行图像优化。它在dev上运行良好,但在生产中不会从外部URL加载图像。
我能做什么?
您需要首先在next.config.js文件中设置配置。
例如:
next.config.js
module.exports = {
images: {
domains: ['images.unsplash.com'],
},
}
在页面/your_page_file.tsx上
<Image
alt="The guitarist in the concert."
src="https://images.unsplash.com/photo-1464375117522-1311d6a5b81f?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=2250&q=80"
width={2250}
height={1390}
layout="responsive"
/>
如果您想在互联网上的nextjs应用程序中显示任何图像;这是我的下一个配置:
const nextConfig = {
reactStrictMode: true,
i18n,
sassOptions: {
includePaths: [path.join(__dirname, 'src/styles')],
prependData: `@import "variables.scss";`,
},
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**',
port: '',
pathname: '**',
},
],
},
}
在下一个配置next.config.js
:中添加并声明您的域
module.exports = {
reactStrictMode: true,
images: {
domains: ["yourDomain.com"],
formats: ["image/webp"],
},
};
配置文件next.config.js
应该位于项目的根目录中。
最后,即使在开发模式下也要重新启动项目。
对于未来的参考,我在将next.js站点部署到Netlify后也遇到了同样的问题。只是后来,在阅读日志时,我发现了
next.config.js中设置的图像域将被忽略。请将env变量NEXT_IMAGE_ALLOWED_DOMAINS设置为";cdn.sanity.io;而是
所以这可能是需要注意的。在我看到它之前,我插入了下一个健全镜像插件https://www.sanity.io/plugins/next-sanity-image到我的页面,它也绕过了问题
对我来说,只是添加了拦截器扩展。