好吧,我想通了。
首先,您可以运行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 中,所有这些都会相应地起作用。