如何在 storybook 上使用 scss 上的静态资产?

How can I use static assets on scss with storybook?

我在 styles/ 文件夹下有一个 scss 库,我有这样的代码:

// Variables
$path-to-img: "/img" !default;
$path-to-fonts: "/fonts" !default;

// Example use case
.bg-pattern-2 {
  background-image: linear-gradient(to bottom, transparent 0%, $black 100%), url('#{$path-to-img}/patterns/pattern-2.png');
}

在Next.js中,我把所有的静态资源都放在了public/文件夹下,所以:

public/
------- img/
------- fonts/
------- ...
       

但是当我尝试 运行 start-storybook -p 9000 它给了我一个错误:

抛出这个错误很有道理,但我该如何真正解决这个问题?

具体用webpack吗?

嗯,我想通了。

首先可以运行yarn storybook --debug-webpack快速浏览一下Webpack的配置结构

经过一些调试,我可以看到 publicPath"",所以这意味着资产需要在 /img 下的 .storybook 文件夹中和 /fonts 个文件夹

为什么?

因为呈现 Storybook 应用程序的 html 输出与注入的 CSS 文件位于同一路径上,其中之一是由 [=45= 给出的 css ]-装载机。

解决方案:

  webpackFinal: async (config, { configType }) => {
    // Add Sass to storybook
    config.module.rules.push({
      test: /\.scss$/,
      include: path.resolve(__dirname, "../styles"),
      use: [
        {
          loader: "style-loader",
        },
        {
          loader: "css-loader",
          options: {
            url: false, // This was the important key ** see explanation
          },
        },
        {
          loader: "sass-loader",
        },
      ],
    });

    // Copy all assets to publicPath
    config.plugins.push(
      new CopyPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "../public/fonts"),
            to: "./fonts", 
          },
          {
            from: path.resolve(__dirname, "../public/img"),
            to: "./img", 
          },
        ],
      })
    );

    return config;
  },

options {url: false} 这是我的问题的关键。嗯,基本上当你有:

// Example use case
.bg-pattern-2 {
  background-image: linear-gradient(to bottom, transparent 0%, $black 100%), url('#{$path-to-img}/patterns/pattern-2.png');
}

css-loader 将创建自己的 url,因此注入的 css 将具有错误的图像路径。

通过禁用它,然后我们可以复制那些带有copy-webpack-plugin的资源到webpack的publicPath,所有的都将相应地运行。