【问题标题】:next/image configuration in Next.js config fileNext.js 配置文件中的 next/image 配置
【发布时间】:2021-06-06 13:55:11
【问题描述】:

我正在我的 Headless 项目中实现 Next.js Image 组件。我使用的 CMS 是 WordPress。由于图片来自外部网站,我需要在 next.config.js 上指定域,如文档所述:

https://nextjs.org/docs/basic-features/image-optimization

const nextConfig = {
    image: {
        domains: ['https://example.com'],
    },
}

但是在我的next.config.js 文件中我已经有了这个配置:

const withStyles = require('@webdeb/next-styles');

module.exports = withStyles({
    sass: true,
    modules: true,
});

所以我的斗争是将这两者结合到配置文件中。

只是在某些情况下,没有图像配置,我有这个错误:

错误:next/image 上的 src 属性无效,您的 next.config.js 中的图像下未配置主机名

我尝试使用next-compose-plugins 将其像下面的代码一样放在一起,但错误一直显示:

const withStyles = require('@webdeb/next-styles');
const withPlugins = require('next-compose-plugins');

const nextConfig = {
    image: {
        domains: ['https://example.com'],
    },
}

module.exports = withPlugins([
    [withStyles({
        sass: true,
        modules: true,
    })]
], nextConfig);

没有在module.exports末尾的nextConfig,代码可以正常工作。

我需要传递的 URL 的一个细节是它是一个子域和一个同源环境,但它不需要访问凭据。我不认为这是问题所在。

由于我是 Next.js 的新手,所以我无法弄清楚这个配置需要如何工作。

【问题讨论】:

    标签: reactjs wordpress next.js nextjs-image


    【解决方案1】:

    你的配置对象应该被传递给最后一个插件调用。因此,在您的情况下,它将如下所示:

    const withStyles = require('@webdeb/next-styles');
    
    module.exports = withStyles({
        sass: true,
        modules: true,
        images: {
            domains: ['https://example.com'],
        }
    });
    

    还要注意next/image 配置的正确条目是images 而不是image。这就是为什么当您尝试使用 next-compose-plugins 时它可能不起作用的原因,因为该代码 sn-p 中的其他所有内容似乎都是正确的。

    【讨论】:

    • 非常感谢。有效。可能最大的问题是末尾没有 s 的图像。但是我不明白的是为什么配置对象可以在 next-styles 包的末尾传递。但这是如何工作的呢?
    • 基本上,插件的工作方式是使用配置对象中的相关字段来完成他们需要做的事情。在这种情况下,withStyles 将使用 sassmodules 字段将适当的 webpack 配置添加到对象,然后返回以由下一个插件处理,依此类推,直到您得到最终的配置对象.
    • 感谢您的解释。现在我更清楚了。
    猜你喜欢
    • 2023-02-04
    • 2020-12-04
    • 2019-06-08
    • 1970-01-01
    • 2021-12-04
    • 2018-11-29
    • 2020-10-29
    • 1970-01-01
    • 2020-01-07
    相关资源
    最近更新 更多