故事书需要导出默认的Ant Design组件以应用样式

时间:2019-10-25 08:38:39

标签: reactjs antd storybook

我希望使用Ant Design设计我的一些React组件,并在Storybook中进行记录。

故事书和组件均正确编写且可以正常工作。

modal.stories.js

import React from "react";
import { action } from "@storybook/addon-actions";
import { Button } from "@storybook/react/demo";
import { BasicModal } from "./BasicModal";
import { Modal } from "antd"; // IF I REMOVE THIS ANT DESIGN DOESN'T APPLY.

export default {
  title: "Modals"
};

export const basicModal = () => <BasicModal visible={true} />;
export const basicModal2 = () => <Modal visible={true} />; //IF I REMOVE THIS ANT DESIGN DOESN'T APPLY.

BasicModal.tsx

import React, { ReactNode } from "react";
import { Modal } from "antd";
interface BasicModalProps {}

export const BasicModal: React.FC<BasicModalProps> = ({}) => {
  return (
    <Modal
      title="Basic Modal"
      visible={true}
    >
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
    </Modal>
  );
};

webpack.config.js

const path = require("path");

module.exports = {
    module: {
        rules: [
            {
                loader: 'babel-loader',
                exclude: /node_modules/,
                test: /\.js$/,
                options: {
                    presets: ["@babel/react"],
                    plugins: [
                        ['import', {libraryName: "antd", style: true}]
                    ]
                },
            },
            {
                test: /\.less$/,
                loaders: [
                    "style-loader",
                    "css-loader",
                    {
                        loader: "less-loader",

                        options: {
                            modifyVars: {"@primary-color": "#d8df19"},
                            javascriptEnabled: true
                        }
                    }
                ],
                include: path.resolve(__dirname, "../")
            }
        ]
    }
};

但是,我遇到了在modal.stories.js中应用样式的问题。如果我不包括import { modal } from 'antd'并使用Modal组件导出常量,那么我的 own 样式的组件将不会应用ant设计样式。

在上面的示例中,我得到了两个模态basicModalbasicModal2,它们都已通过ant-design进行了样式设置。但是,如果我将basicModal2注释掉,则basicModal会恢复为默认的CSS样式。

是否可以解决此问题,而不必在每个故事中添加默认的Ant Design组件?

2 个答案:

答案 0 :(得分:1)

在故事书的antd文件中导入import 'antd/dist/antd.css';样式config.js

// @ .storybook/config.js 
import { configure } from '@storybook/react';
import 'antd/dist/antd.css';

function loadStories() {
  const req = require.context('stories', true, /\.stories\.js$/);
  req.keys().forEach(filename => req(filename));
}

configure(loadStories, module);

请参阅storybook文档中的CSS Support

答案 1 :(得分:1)

Storybook v6

进入(或创建).storybook/preview.js,然后在顶部添加import 'antd/dist/antd.css';


示例.storybook/preview.js

import 'antd/dist/antd.css';

export const parameters = {
    actions: { argTypesRegex: '^on[A-Z].*' },
};