在现有NX项目中使用Storybook遇报错问题求助
解决NX React项目中Storybook配置及stories生成问题
1. 配置后无可用stories & 生成命令无输出
- 检查项目配置:确认
ui项目的project.json中存在storybook和stories目标,且stories生成器配置正确,示例如下:"stories": { "executor": "@nx/react:stories", "options": { "project": "apps/ui/project.json", "generateStories": true, "generateCypressSpecs": false } } - 修正生成命令:你使用的命令参数有误,正确的stories生成命令是:
无需添加nx generate @nx/react:stories --project=ui--target=storybook,该参数不属于stories生成器的选项。 - 自定义组件路径配置:如果
ui项目的组件不在默认扫描路径(如src/lib或src/components),需在project.json的storybook目标options中指定扫描路径:"storybook": { "executor": "@nx/react:storybook", "options": { "stories": ["apps/ui/src/**/*.stories.tsx"], "config": { "configFolder": "apps/ui/.storybook" } } }
2. 手动编写stories报错"Invariant failed: makeTitle created an undefined title"
该错误多因NX封装的makeTitle函数参数缺失或格式错误导致,可按以下方式解决:
- 正确使用
makeTitle:确保传入项目名和组件名两个参数,示例:import { makeTitle } from '@nx/react'; import Logo from './Logo'; export default { title: makeTitle('ui', 'Logo'), component: Logo, }; - 绕过
makeTitle直接定义标题:如果仍有问题,可手动指定层级标题:export default { title: 'UI/Logo', component: Logo, }; - 检查Storybook配置文件:确认
.storybook/main.js的stories数组包含你的手动编写文件路径:module.exports = { stories: ['../src/**/*.stories.tsx'], addons: ['@storybook/addon-essentials'], framework: '@storybook/react', };
额外排查步骤
- 清理NX缓存:执行
nx reset清除缓存后,重新运行生成命令和Storybook。 - 版本兼容性:确认NX与
@nx/react、@storybook/react版本匹配(如NX 16+对应Storybook 7+),避免版本冲突。 - 组件导出检查:确保
Logo.tsx为默认导出或正确命名导出,保证stories文件能正常导入组件。
内容的提问来源于stack exchange,提问作者Dmitry Malugin
相关产品推荐
相关产品推荐

