无法正确设置 next-config 故事书以从 url 获取图像

Can't properly set up next-config storybook to get images from url

我正在尝试从故事书中的 url 导入图像。在 nextJS 中,除非您允许,否则图像不能来自域。 我允许它在 next-config.js 文件中执行以下操作:

module.exports = {
  env: {
    API: process.env.API
  },
  images: {
    domains: ['https://sourceexample.com/image']
  }
};

它适用于使用常规 next dev 在故事书之外制作页面。但是,当我尝试呈现具有此组件的同一页面时:

      <Image
       alt="example"
       src="https://sourceexample.com/image.png"
       width="auto"
       height="auto"
     />

当我没有在 next-config.js 中添加允许的域时,它显示了完全相同的错误,即: Invalid src prop (https://sourceexample.com/image.png) on `next/image`, hostname "source" is not configured under images in your `next.config.js

我想也许是因为我应该将 next-config.js 导入到故事书配置中,所以我 google 为此偶然发现了这段代码,我不知道该怎么做用它。这段代码写在 "How do I setup Storybook to share Webpack configuration with Next.js?" in the storyboook documentation.

module.exports = {
  webpackFinal: async (baseConfig) => {
    const nextConfig = require('/path/to/next.config.js');

    // merge whatever from nextConfig into the webpack config storybook will use
    return { ...baseConfig };
  },

我尝试扩展 nextConfig 中的属性,例如添加 return {...baseConfig, ...nextConfig} 在 return 方法中。它没有用。有人可以解释这里发生了什么以及我应该如何使用它吗?

我 运行 解决了这个问题,并通过在 storybook 的 webpack 配置中模拟 'next/image' 解决了它(请参阅下面的 link 中的详细信息)

https://storybook.js.org/docs/react/workflows/build-pages-with-storybook#mocking-imports

创建一个新的 React 组件文件:

// file: .storybook/__mocks__/NextJSImageMock.js

import React from "react";

export default function NextImageMock(props) {
  return <img {...props} />;
}

然后,覆盖导入:

// file: .storybook/webpack.config.js

module.exports = ({ config }) => {
  config.resolve.alias = {
    "next/image": require.resolve("./__mocks__/NextJSImageMock.js"),
  };

  return config;
};

只需将此代码添加到 .storybook/preview.js 文件中:

import * as nextImage from 'next/image';

Object.defineProperty(nextImage, 'default', {
  configurable: true,
  value: props => <img {...props} />
});

更新:似乎这个插件解决了这个问题 - https://storybook.js.org/addons/storybook-addon-next