在storybook中使用antd
最近一個 react 的專案有用到了 antd 這個 ui 庫。這裡作個筆記記錄一下如何在 storybook 中顯示 antd 的元件。
專案是使用 create-react-app
建立的,專案目錄結構如下:
├── .storybook/ ├── README.md ├── antd-theme.js ├── node_modules ├── package.json ├── public └── src ├── App.js ├── components │ ├── button.js │ └── button.stories.js ├── index.js └── registerServiceWorker.js
這裡建立了一個 button
元件,內容如下:
// src/components/button.js import React, { Component, Fragment } from 'react'; import { Button } from 'antd'; class ButtonGhostextends Component{ render() { return ( <Fragment> <h3 className="ex-title">Ghost Button</h3> <div style={{ background: 'rgb(47, 45, 165)', padding: '26px 16px 16px' }}> <Button type="primary">Primary</Button> <Button className="ml20" ghost>Default</Button> <Button className="ml20" type="dashed" ghost>Dashed</Button> <Button className="ml20" type="danger" ghost>danger</Button> </div> </Fragment> ); } } export default ButtonGhost;
對應的 storybook 案例如下:
// src/components/button.stories.js import React from 'react'; import { storiesOf } from '@storybook/react'; import Button from './button'; storiesOf('General', module) .add('Button', () => <Button />)
然後 storybook 配置如下:
// .storybook/config.js import React from 'react' import { configure } from '@storybook/react' import { ThemeProvider} from 'styled-components' const req = require.context('../src/components', true, /\.stories\.js$/) function loadStories(){ req.keys().forEach((filename) => req(filename)) } configure(loadStories, module)
然後執行 storybook : start-storybook -p 6006 -c .storybook
,效果如下:
這是由於 antd 的 css 沒有載入,因此所有按鈕的樣式都沒有。
參考 ofollow,noindex">https://ant.design/docs/react/use-with-create-react-app-cn 的說明,修改 babel 和 webpack 的配置。
參考 https://storybook.js.org/configurations/custom-webpack-config 的說明,修改 storybook 的 webpack 配置。
建立檔案 .storybook/.babelrc
:
{ "presets": [ [ "env", { "modules": false, "targets": { "browsers": [ ">1%", "last 4 versions", "Firefox ESR", "not ie < 11" ] } } ], "react", "stage-3" ], "plugins": [ [ "import", { "libraryName": "antd", "style": true } ] ] }
建立檔案 .storybook/webpack.config.js
:
module.exports = { module: { rules: [ { test: /\.less$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "less-loader", options: { //modifyVars: antdTheme, // 如果要自定義主題樣式 javascriptEnabled: true } }] } ] } };
然後在 .storybook/config.js
檔案新增 import 'antd/dist/antd.less';
。
最後的效果如下:
