简体   繁体   English

next/image 部署后不从外部 URL 加载图像

[英]next/image does not load images from external URL after deployment

I use the Next.js Image component for image optimization.我使用 Next.js Image组件进行图像优化。 It works great on dev but it doesn't load images from external URLs in production.它在 dev 上工作得很好,但它不会在生产中从外部 URL 加载图像。

What can I do?我能做些什么?

You need to set configuration on the next.config.js file first 您需要先在 next.config.js 文件上设置配置

Example:例子:

on next.config.jsnext.config.js

module.exports = {
    images: {
        domains: ['images.unsplash.com'],
    },
}

on pages/your_page_file.tsx页面/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"
/>

For future references, I was having the same problem after deploying my next.js site to Netlify.为了将来参考,在将我的 next.js 站点部署到 Netlify 后,我遇到了同样的问题。 Only later, reading my logs, I found只是后来,阅读我的日志,我发现

Image domains set in next.config.js are ignored.在 next.config.js 中设置的图像域被忽略。 Please set the env variable NEXT_IMAGE_ALLOWED_DOMAINS to "cdn.sanity.io" instead请改为将环境变量 NEXT_IMAGE_ALLOWED_DOMAINS 设置为“cdn.sanity.io”

So this is probably something to note.所以这可能是需要注意的。 In the meanwhile before I saw it, I plugged this next-sanity-image plugin https://www.sanity.io/plugins/next-sanity-image to my page, which also bypassed the problem与此同时,在我看到它之前,我将这个 next-sanity-image 插件https://www.sanity.io/plugins/next-sanity-image插入我的页面,这也绕过了问题

add and declare your domain to next config将您的域添加并声明到下一个配置

 module.exports = { reactStrictMode: true, images: { domains: ["yourDomain.com"], formats: ["image/webp"], }, };

in next.config.js on root of your project在项目根目录的 next.config.js 中

ans restart project even in dev mod即使在开发模式中也可以重新启动项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM