Next.js - 我可以在 next.config.js 中配置多个图像主机名吗?

Enb*_*eur 5 next.js

我在 next.config.js 中编写了下面的代码

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: [
          'images.unsplash.com',
          'hydeparkwinterwonderland.com',
          'wembleypark.com']
      },
    ]
  }
}

module.exports = nextConfig
Run Code Online (Sandbox Code Playgroud)

但它会抛出这样的错误:

- The value at .images.remotePatterns[0].hostname must be a string but it was an array.

See more info here: https://nextjs.org/docs/messages/invalid-next-config
Run Code Online (Sandbox Code Playgroud)
Error: Invalid images.remotePatterns values:
{"protocol":"https","hostname":["images.unsplash.com","hydeparkwinterwonderland.com","wembleypark.com"]}

remotePatterns value must follow format { protocol: 'https', hostname: 'example.com', port: '', pathname: '/imgs/**' }.
See more info here: https://nextjs.org/docs/messages/invalid-images-config
Run Code Online (Sandbox Code Playgroud)

正在寻找答案,我是新手,请耐心等待

Nic*_* Vu 18

hostname只允许单个值,因此您无法传递主机名数组。相反,您可以在remotePatterns.

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.unsplash.com'
      },
      {
        protocol: 'https',
        hostname: 'hydeparkwinterwonderland.com'
      },
      {
        protocol: 'https',
        hostname: 'wembleypark.com'
      },
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

或者减少重复的代码map

const hostnames = [
          'images.unsplash.com',
          'hydeparkwinterwonderland.com',
          'wembleypark.com']

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    remotePatterns: hostnames.map(hostname => ({
        protocol: 'https',
        hostname
    }))
  }
}
Run Code Online (Sandbox Code Playgroud)