我有一个现有的GatsbyJS项目,我想将Storybook添加到该项目中,以展示每个单独的组件。我在我的项目中使用SCSS,这些项目正在使用gatsby-plugin-sass
进行编译,效果很好。但是,由于无法编译SCSS
文件,因此无法在Storybook中使用我的组件。
我遵循了Storybook和GatsbyJS的指示。这就是我的storybook/webpack.config.js的样子:
module.exports = ({ config }) => {
// Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
config.module.rules[0].exclude =
[
/node_modules\/(?!(gatsby)\/)/,
];
// use installed babel-loader which is v8.0-beta (which is meant to work with @babel/core@7)
config.module.rules[0].use[0].loader = require.resolve('babel-loader');
// use @babel/preset-react for JSX and env (instead of staged presets)
config.module.rules[0].use[0].options.presets = [
require.resolve('@babel/preset-react'),
require.resolve('@babel/preset-env'),
];
config.module.rules[0].use[0].options.plugins = [
// use @babel/plugin-proposal-class-properties for class arrow functions
require.resolve('@babel/plugin-proposal-class-properties'),
// use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
require.resolve('babel-plugin-remove-graphql-queries'),
];
// Prefer Gatsby ES6 entrypoint (module) over commonjs (main) entrypoint
config.resolve.mainFields = ['browser', 'module', 'main'];
return config;
};
我的storybook/config.js文件如下所示:
import { configure } from '@storybook/react';
import { action } from '@storybook/addon-actions';
// automatically import all files ending in *.stories.js
configure(require.context('../src', true, /\.stories\.js$/), module);
// Gatsby's Link overrides:
// Gatsby defines a global called ___loader to prevent its method calls from creating console errors you override it here
global.___loader = {
enqueue: () => {
},
hovering: () => {
},
};
// Gatsby internal mocking to prevent unnecessary errors in storybook testing environment
global.__PATH_PREFIX__ = '';
// This is to utilized to override the window.___navigate method Gatsby defines and uses to report what path a Link would be taking us to if it wasn't inside a storybook
window.___navigate = pathname => {
action('NavigateTo:')(pathname);
};
我假设我需要在webpack配置中添加一个sass-loader,但是添加另一个自定义加载器确实有些不自然,因为GatsbyJS已经处理了我的SCSS文件。
我一直在把sass-loader,css-loader和style-loader添加到我的webpack.config.js中,但是我无法使其正常工作。
同样,谷歌搜索这种特定情况并不会给我带来很多成功。我认为我不是第一个尝试这样做的人。
最佳答案
安装此npm软件包:
npm install sass-loader node-sass webpack --save-dev
然后在 .storybook 文件夹中创建一个名称为 webpack.config.js 的文件,并将这些配置粘贴到此文件上:
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
};
关于reactjs - 使用Gatsby在Storybook中编译SCSS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58768253/