Next.js 配置文件中的 next/image 配置

Gra*_*lho 6 wordpress reactjs next.js nextjs-image

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

\n

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

\n
const nextConfig = {\n    image: {\n        domains: [\'https://example.com\'],\n    },\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但在我的next.config.js文件 I\xe2\x80\x99ve 已经有这个配置:

\n
const withStyles = require(\'@webdeb/next-styles\');\n\nmodule.exports = withStyles({\n    sass: true,\n    modules: true,\n});\n
Run Code Online (Sandbox Code Playgroud)\n

所以我的努力​​是将这两者结合在配置文件中。

\n

仅对于某些上下文,没有图像配置,我遇到此错误:

\n
\n

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

\n
\n

在此输入图像描述

\n

我尝试使用以下代码将其组合在一起next-compose-plugins,但错误不断显示:

\n
const withStyles = require(\'@webdeb/next-styles\');\nconst withPlugins = require(\'next-compose-plugins\');\n\nconst nextConfig = {\n    image: {\n        domains: [\'https://example.com\'],\n    },\n}\n\nmodule.exports = withPlugins([\n    [withStyles({\n        sass: true,\n        modules: true,\n    })]\n], nextConfig);\n
Run Code Online (Sandbox Code Playgroud)\n

如果 module.exports 末尾没有 nextConfig,则代码可以正常工作。

\n

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

\n

由于我是 Next.js 的新手,我只是不知道这个配置需要如何工作。

\n

jul*_*ves 5

您的配置对象应该传递给最后一个插件调用。所以在你的情况下它看起来像下面这样:

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

module.exports = withStyles({
    sass: true,
    modules: true,
    images: {
        domains: ['https://example.com'],
    }
});
Run Code Online (Sandbox Code Playgroud)

另请注意,正确的配置条目next/imageimages且不是image。这就是为什么当您尝试使用 时它可能不起作用next-compose-plugins,因为该代码片段中的其他所有内容似乎都是正确的。

  • 本质上,插件的工作方式是使用配置对象中的相关字段来完成它们需要执行的操作。在这种情况下,`withStyles`将使用`sass`和`modules`字段将适当的webpack配置添加到对象中,然后返回该对象以供下一个插件处理,依此类推,直到您得到最终的配置对象。 (2认同)