我使用Next.js的Image
组件进行图像优化。在开发环境中它效果很好,但是在生产环境中无法从外部URL加载图像。
我该怎么办?
我使用Next.js的Image
组件进行图像优化。在开发环境中它效果很好,但是在生产环境中无法从外部URL加载图像。
我该怎么办?
首先,您需要在next.config.js文件中进行配置设置。
例如:
在next.config.js文件中:
module.exports = {
images: {
domains: ['images.unsplash.com'],
},
}
<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"
/>
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'assets.example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
remotePatterns
来进行更具体的配置。
请参见https://nextjs.org/docs/messages/next-image-unconfigured-host(domains
键仍然是可行的解决方案) - damjuve
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
应该放在项目的根目录下。
最后,在dev模式下也需要重新启动项目。
供日后参考,我在将next.js站点部署到Netlify后遇到了同样的问题。只有在阅读我的日志后,我才发现:
在next.config.js中设置的图像域被忽略。 请将环境变量NEXT_IMAGE_ALLOWED_DOMAINS设置为"cdn.sanity.io"
因此这可能是需要注意的事项。在我看到这个之前,我使用了next-sanity-image插件https://www.sanity.io/plugins/next-sanity-image来解决这个问题。
/** @type {import('next').NextConfig} */
const path = require('path')
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**',
port: '',
pathname: '**',
},
],
},
}
module.exports = nextConfig
对我来说,只需要添加广告拦截器扩展程序。