【发布时间】:2021-03-15 08:34:47
【问题描述】:
我使用 Next.js Image 组件进行图像优化。它在开发环境中运行良好,但在生产环境中无法从外部 URL 加载图像。
我能做什么?
【问题讨论】:
标签: reactjs next.js nextjs-image
我使用 Next.js Image 组件进行图像优化。它在开发环境中运行良好,但在生产环境中无法从外部 URL 加载图像。
我能做什么?
【问题讨论】:
标签: reactjs next.js nextjs-image
You need to set configuration on the next.config.js file first
示例:
关于next.config.js
module.exports = {
images: {
domains: ['images.unsplash.com'],
},
}
在 pages/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"
/>
【讨论】:
为了将来的参考,我在将 next.js 站点部署到 Netlify 后遇到了同样的问题。直到后来,阅读我的日志,我才发现
在 next.config.js 中设置的图像域被忽略。 请改为将环境变量 NEXT_IMAGE_ALLOWED_DOMAINS 设置为“cdn.sanity.io”
所以这可能需要注意。在我看到它之前,我将这个next-sanity-image插件https://www.sanity.io/plugins/next-sanity-image插入我的页面,这也绕过了这个问题
【讨论】:
在您的下一个配置中添加并声明您的域,next.config.js:
module.exports = {
reactStrictMode: true,
images: {
domains: ["yourDomain.com"],
formats: ["image/webp"],
},
};
配置文件next.config.js 应位于项目的根目录中。
最后,即使在开发模式下也要重新启动项目。
【讨论】: