无法在NextJs + Storybook中提供静态文件

xpszyzbs  于 2023-10-18  发布在  其他
关注(0)|答案(3)|浏览(162)

nextjs docs(https://nextjs.org/docs/basic-features/static-file-serving)声明在public目录下添加图像文件路径。
我有一个渲染图像组件的组件,该文件在我的nextjs项目中正确渲染,但在storybook中无法渲染。图像文件当前位于public/images/

const renderImage = () => {
    const portraitClassName = cx({
        [styles.imageContainerPortrait]: true,
    });

    return (
        <img
            className={portraitClassName}
            data-testid="image"
            src="/images/portrait.png"
            alt={image.imgAlt}
        />
    );
};

这是我目前的配置文件的故事书

webpackFinal: async (config) => {
        config.module.rules.push({
            test: /\.(scss|sass|css)$/,
            use: [
                {
                    loader: "sass-loader",
                    options: {
                        implementation: require("sass"),
                    },
                },
                {
                    loader: "postcss-loader",
                    options: {
                        ident: "postcss",
                        plugins: [tailwindcss, autoprefixer],
                    },
                }
            ],
            include: path.resolve(__dirname, "../"),
        });
        return config;
    }

是否缺少了一些东西,可以让我以与Nextjs设置相同的方式渲染图像?

vof42yt1

vof42yt11#

你需要告诉故事书在哪里可以找到你的图像。在nextjs中,它们仍然在public/中,因此您可以将-s ./public添加到脚本中以运行storybook:

//package.json
{
"scripts": {
    "start-storybook": "start-storybook -s ./public"
  }
}

这里的文档链接供参考:https://storybook.js.org/docs/react/configure/images-and-assets#serving-static-files-via-storybook

ssm49v7z

ssm49v7z2#

你需要像这样修改.storybook/preview.js文件:

import * as NextImage from 'next/image';

const OriginalNextImage = NextImage.default;

Object.defineProperty(NextImage, 'default', {
  configurable: true,
  value: (props) => (
    <OriginalNextImage
      {...props}
      unoptimized
      blurDataURL="data:image/jpeg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAADAAQDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAbEAADAAMBAQAAAAAAAAAAAAABAgMABAURUf/EABUBAQEAAAAAAAAAAAAAAAAAAAMF/8QAFxEAAwEAAAAAAAAAAAAAAAAAAAECEf/aAAwDAQACEQMRAD8Anz9voy1dCI2mectSE5ioFCqia+KCwJ8HzGMZPqJb1oPEf//Z"
    />
  ),
});
gcuhipw9

gcuhipw93#

对我有用的是,我需要使用staticDirs告诉storybook.js我的公共资源位于何处。
即:根目录>.storybook目录> main.ts

const config: StorybookConfig = {
 //other stuff .... 
  docs: {
    autodocs: 'tag',
  },

  staticDirs: ['../public/'], //<--- FIX    };

};
export default config;

相关问题