stories
(必需)
类型
| (string | StoriesSpecifier)[]
| async (list: (string | StoriesSpecifier)[]) => (string | StoriesSpecifier)[]
配置 Storybook 从指定位置加载故事。其目的是让你将故事文件与它记录的组件放在一起。
•
└── components
├── Button.ts
└── Button.stories.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
framework: '@storybook/your-framework',
stories: ['../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
};
export default config;
如果你想使用不同的命名约定,可以使用 picomatch 支持的语法更改 glob 表达式。
请记住,某些插件可能假定 Storybook 的默认命名约定。
使用 glob 表达式数组
Storybook 将根据这个 glob 表达式数组(模式匹配字符串)从你的项目中加载故事。
故事按照它们在数组中定义的顺序加载。这使你可以控制故事在侧边栏中的显示顺序。
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
framework: '@storybook/your-framework',
stories: ['../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
};
export default config;
使用配置对象
此外,你可以自定义 Storybook 配置,根据配置对象加载你的故事。此对象的类型为 StoriesSpecifier
,定义如下。
例如,如果你想从 packages/components
目录加载故事,可以将 stories
配置字段调整如下
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { StorybookConfig } from '@storybook/your-framework';
const config: StorybookConfig = {
framework: '@storybook/your-framework',
stories: [
{
// 👇 Sets the directory containing your stories
directory: '../packages/components',
// 👇 Storybook will load all files that match this glob
files: '*.stories.*',
// 👇 Used when generating automatic titles for your stories
titlePrefix: 'MyComponents',
},
],
};
export default config;
当 Storybook 启动时,它将在 packages/components
目录中查找包含 stories
扩展名的文件,并为你的故事生成标题。
StoriesSpecifier
类型
{
directory: string;
files?: string;
titlePrefix?: string;
}
StoriesSpecifier.directory
(必需)
类型:string
相对于项目根目录,开始查找故事文件的位置。
StoriesSpecifier.files
类型:string
默认值:'**/*.@(mdx|stories.@(js|jsx|mjs|ts|tsx))'
一个 glob 表达式,相对于 StoriesSpecifier.directory
(不包含开头的 ./
),用于匹配要加载的文件名。
StoriesSpecifier.titlePrefix
类型:string
默认值:''
自动生成标题时,用于为你的故事生成标题的前缀。
使用自定义实现
💡 Storybook 现在会静态分析配置文件以提高性能。使用自定义实现加载故事可能会导致性能下降或破坏此能力。
你还可以调整 Storybook 配置并实现自定义逻辑来加载你的故事。例如,假设你在一个项目中工作,该项目包含一种常规方式无法解决的特定模式。在这种情况下,你可以按如下方式调整配置
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { StorybookConfig } from '@storybook/your-framework';
import type { StoriesEntry } from 'storybook/internal/types';
async function findStories(): Promise<StoriesEntry[]> {
// your custom logic returns a list of files
}
const config: StorybookConfig = {
framework: '@storybook/your-framework',
stories: async (list: StoriesEntry[]) => [
...list,
// 👇 Add your found stories to the existing list of story files
...(await findStories()),
],
};
export default config;