Angular 19与Storybook 8.4.4兼容问题:仍需显式声明standalone选项
我将Angular UI库升级到Angular 19和Storybook 8.4.4(均为当前最新版本)后遇到了问题。Angular 19中独立组件成为默认选项,组件装饰器不再需要显式声明standalone: true:
Angular 19之前(14-18版本)的写法
@Component({ standalone: true, imports: [CommonModule], selector: 'app-my-component', templateUrl: './my-component.html', }) export class MyComponent { }
Angular 19的写法(无需显式standalone)
@Component({ imports: [CommonModule], selector: 'app-my-component', templateUrl: './my-component.html', }) export class MyComponent { }
但运行Storybook时触发如下报错:
Error: Unexpected "ButtonComponent" found in the "declarations" array of the "StorybookComponentModule" NgModule. ButtonComponent" is marked as standalone and can't be declared in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?
问题原因
Storybook会在内部生成临时Angular模块StorybookComponentModule,用于包裹组件及其元数据,但它会尝试将组件加入该模块的declarations数组。而Angular 19中隐式设置为独立的组件,会被识别为独立组件,这类组件不允许被声明在NgModule的declarations中,只能通过imports引入,因此触发了上述错误。
解决方案
目前唯一可行的解决办法是手动为所有组件(推测管道、指令也存在相同问题)显式添加standalone: true选项,恢复到Angular 19之前的写法,避免Storybook的临时模块处理逻辑报错。
内容的提问来源于stack exchange,提问作者Kurt Van den Branden

