【问题标题】:How can I use static assets on scss with storybook?如何在带有故事书的 scss 上使用静态资产?
【发布时间】:2021-05-30 06:37:42
【问题描述】:

我在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?

【问题讨论】:

    标签: webpack next.js webpack-4 storybook


    【解决方案1】:

    好吧,我想通了。

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

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

    为什么?

    因为渲染 Storybook 应用程序的 html 输出与注入的 CSS 文件位于同一路径上,其中之一是 sass-loader 给出的 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 中,所有这些都会相应地起作用。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2019-11-16
    • 2021-12-13
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    相关资源
    最近更新 更多