【问题标题】:How to mock Next.js Image component in Storybook?如何在 Storybook 中模拟 Next.js Image 组件?
【发布时间】:2021-02-13 18:20:12
【问题描述】:

Next.js 在 v10 中引入了一个新的 Image 组件,它应该是 <img> 标记的替代品。

我在尝试查看将 next/image 导入 Storybook 的组件时出错:

TypeError: imageData is undefined

我一直在尝试覆盖 preview.js 中的图像对象(我用于 next/router 的技术,如文档中的 here 所述)但我得到了同样的错误:

// .storybook/preview.js

import Image from 'next/image';

Image = ({ src }) => <img src={src} />;

知道如何覆盖 Storybook 中 next/image 包的行为吗?

【问题讨论】:

    标签: javascript reactjs next.js storybook nextjs-image


    【解决方案1】:

    我终于成功了。

    首先我们需要使用默认设置定义一个环境变量来消除错误。我们可以通过在.storybook/main.js 中插入 webpack 来做到这一点:

    // .storybook/main.js
    var webpack = require('webpack');
    
    module.exports = {
      ...
      webpackFinal: (config) => {
        config.plugins.push(new webpack.DefinePlugin({
          'process.env.__NEXT_IMAGE_OPTS': JSON.stringify({
            deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
            imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
            domains: [],
            path: '/',
            loader: 'default',
          }),
        }));
        return config;
      },
    };
    

    现在我们可以用一个返回简单&lt;img/&gt;标签的功能组件覆盖next/image包的默认导出。

    // .storybook/preview.js
    
    import * as nextImage from 'next/image';
    
    Object.defineProperty(nextImage, 'default', {
      configurable: true,
      value: (props) => {
        return <img {...props} />;
      },
    });
    

    我为此使用 defineProperty 静态方法 (link to MDN article),因为我不能只为 Image.default 分配一个新值。

    【讨论】:

    • 请注意,截至此评论日期,这仅与 webpack v4 兼容,而不与 v5 兼容
    • @OmarNasr 由于 NextJS 11 将使用 webpack 5,我期待一个兼容的解决方案
    【解决方案2】:

    作为已接受答案的补充:

    添加var webpack = require('webpack');inside main.js

    【讨论】:

      猜你喜欢
      • 2022-08-24
      • 2022-06-15
      • 2021-01-04
      • 2021-02-16
      • 2021-06-27
      • 2018-12-25
      • 2021-11-17
      • 2021-05-29
      • 2022-11-11
      相关资源
      最近更新 更多