我已经用 Gatsby.js(使用 React 的静态网站生成器)建立了一个网站,并正在尝试向其中添加故事书。
我在故事书中添加了一个自定义 webpack 配置(按照https://storybook.js.org/configurations/custom-webpack-config/中的说明)来加载 sass 和 sass-resources,但无法使其工作。
以下是配置。除了最初的那些之外,我已经为“storybook/react”安装了所有的“style-loader”、“css-loader”、“sass-loader”、“sass-resources-loader”以及“node-sass”添加到“gatsby”和“gatsby-plugin-sass”作为依赖项。
如果有人好心建议,那就太好了。非常感谢您提前提供的帮助。
结构体
root - .storybook - addon.js
- config.js
- webpack.config.js
- src - components - Component_1 - Component_1.js
- Component_1.scss
- Component_1.stories.js
- ...
- styles - _variables.scss
- mixins - _mixin_1.scs
- ...
- ...
- ...
webpack.config.js (root/.storybook/webpack.config.js)
const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\.scss$/,
loaders: [
"style-loader",
"css-loader",
"sass-loader",
{
loader: "sass-resources-loader",
options: {
resources: [
"src/styles/_variables.scss",
"src/styles/mixins/**/*.scss"
]
},
},
],
include: path.resolve(__dirname, "../")
}
]
}
};
component_1.stories.js
import React from "react";
import { storiesOf } from "@storybook/react";
import Component_1 from "./Component_1";
storiesOf("Component_1", module)
.addDecorator(story => (
<div style={{backgroundColor: $color-primary}}>
{story()}
</div>
))
.add("default", () => (
<Component_1>
This is Component 1!
</Component_1>
));
错误消息(显示在故事书应用程序上)
$color is not defined
ReferenceError: $grey is not defined
at http://localhost:6006/static/preview.bundle.js:80090:33
at http://localhost:6006/static/preview.bundle.js:57555:14
at http://localhost:6006/static/preview.bundle.js:57556:16
at WrapStory.render(http://localhost:6006/static/preview.bundle.js:61197:14)
at http://localhost:6006/static/preview.bundle.js:44767:21
at measureLifeCyclePerf (http://localhost:6006/static/preview.bundle.js:44047:12)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (http://localhost:6006/static/preview.bundle.js:44766:25)
at ReactCompositeComponentWrapper._renderValidatedComponent (http://localhost:6006/static/preview.bundle.js:44793:32)
at ReactCompositeComponentWrapper.performInitialMount (http://localhost:6006/static/preview.bundle.js:44333:30)
at ReactCompositeComponentWrapper.mountComponent (http://localhost:6006/static/preview.bundle.js:44229:21)
在这种情况下,sass 变量“$color-primary”在“src/styles/_variables.scss”中定义。我想用它来设置故事书应用程序中显示的 Component_1 的样式。
我尝试将“_variables.scss”明确导入“Component_1.stories.js”并再次失败(跳过“sass-resources-loader”,只使用“sass-loader”)。
谢谢你的建议。
[编辑]
除了上面,我的故事书配置文件如下。
config.js (根/.storybook/config.js)
import { configure, addDecorator } from "@storybook/react";
// automatically import all files ending in *.stories.js
const req = require.context('../src/components', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);