React:如何将 Storybook .stories 放在每个组件的目录中?
Posted
技术标签:
【中文标题】React:如何将 Storybook .stories 放在每个组件的目录中?【英文标题】:React: How to place Storybook .stories in each component's directory? 【发布时间】:2020-07-30 10:33:28 【问题描述】:目前我所有的.stories
文件都保存在stories
目录中。随着我添加更多组件,这将增长。
相反,我想在组件级别添加每个组件的 .stories
文件,根据 Storybook 网站上的文档:https://storybook.js.org/docs/basics/writing-stories/#loading-stories-dynamically
问题是我不知道该怎么做。
我已经设置了以下简单组件(同一目录中的所有文件):
PageTitle.tsx
import React from 'react'
import Typography from '@material-ui/core';
import makeStyles from "@material-ui/styles";
const useStyles = makeStyles(() => (
typographyStyles:
flex: 1
));
interface PageTitleProps
title: string;
const PageTitle = ( title : PageTitleProps) =>
const classes = useStyles()
return (
<Typography className=classes.typographyStyles variant="h1" component="h2">
title
</Typography>
)
;
export default PageTitle;
index.tsx
import PageTitle from './PageTitle';
export default PageTitle;
index.stories.tsx
import React from 'react';
import storiesOf from '@storybook/react'
import FormPageTitle from './index';
export default
title: 'Titles|PageTitle',
component: PageTitle,
;
export const withText = () =>
return <PageTitle title="Hello World" />;
;
在我的.storybook
目录中,我有一个main.js
文件,其中包含:
module.exports =
stories: ['../src/**/*.stories.tsx'],
addons: [
'@storybook/preset-create-react-app',
'@storybook/addon-actions',
'@storybook/addon-links',
name: '@storybook/addon-docs',
options:
configureJSX: true,
,
,
],
;
但我只是得到错误:
找不到模块:错误:无法解析 './index' in '/myApp/src/stories'
无论我如何称呼 .stories 文件,都会发生这种情况。
有人知道正确的设置方法吗?
【问题讨论】:
【参考方案1】:在您的.storybook
目录中创建一个config.js
有
import React from 'react';
import configure, addDecorator from '@storybook/react';
import action from '@storybook/addon-actions';
import styled from 'styled-components';
const Wrapper = styled.div`
display: flex;
flex: 1;
height: 100vh;
align-items: center;
justify-content: center;
`;
const Decorator = (storyFn) => <Wrapper>storyFn()</Wrapper>;
addDecorator(Decorator);
global.___loader =
enqueue: () => ,
hovering: () => ,
;
global.__PATH_PREFIX__ = '';
window.___navigate = (pathname) =>
action('NavigateTo:')(pathname);
;
const req = require.context('../src/components/', true, /\.stories\.js$/);
function loadStories()
req.keys().forEach((filename) => req(filename));
configure(loadStories, module);
【讨论】:
以上是关于React:如何将 Storybook .stories 放在每个组件的目录中?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Storybook React App 中嵌入 StencilJS 组件?
如何导出在 storybook 中创建的 React Native 组件以便在实际应用中使用?