适用于 Angular 的 Storybook
Storybook for Angular 是一个 framework,它可以轻松地为 Angular 应用单独开发和测试 UI 组件。它使用 Angular 构建器并与 Compodoc 集成,以提供自动文档生成功能。
¥Storybook for Angular is a framework that makes it easy to develop and test UI components in isolation for Angular applications. It uses Angular builders and integrates with Compodoc to provide automatic documentation generation.
安装
¥Install
要在现有的 Angular 项目中安装 Storybook,请在项目根目录下运行以下命令:
¥To install Storybook in an existing Angular project, run this command in your project's root directory:
npm create storybook@latest接下来,你可以开始使用 写故事、运行测试 和 组件文档。要更好地控制安装过程,请参阅 安装指南。
¥You can then get started writing stories, running tests and documenting your components. For more control over the installation process, refer to the installation guide.
要求
¥Requirements
Angular ≥ 18.0 < 21.0
Webpack 5
运行 Storybook
¥Run Storybook
要为特定项目运行 Storybook,请运行以下命令:
¥To run Storybook for a particular project, run the following:
ng run <your-project>:storybook要构建 Storybook,请运行:
¥To build Storybook, run:
ng run <your-project>:build-storybook你将在配置的 outputDir(默认为 dist/storybook/<your-project>)中找到输出。
¥You will find the output in the configured outputDir (default is dist/storybook/<your-project>).
配置
¥Configure
为了在 Angular 项目中充分利用 Storybook,你可以根据项目需求设置 Compodoc 集成和 Storybook decorators。
¥To make the most out of Storybook in your Angular project, you can set up Compodoc integration and Storybook decorators based on your project needs.
Compodoc
你可以在组件、指令和 Angular 代码的其他部分上方包含 JSDoc 注释,以包含这些元素的文档。Compodoc 将这些注释用于你的应用的 生成文档。在 Storybook 中,在 @Inputs 和 @Outputs 上方添加解释性注释很有用,因为这些是 Storybook 在其用户界面中显示的主要元素。@Inputs 和 @Outputs 是你可以在 Storybook 中交互的元素,例如 controls。
¥You can include JSDoc comments above components, directives, and other parts of your Angular code to include documentation for those elements. Compodoc uses these comments to generate documentation for your application. In Storybook, it is useful to add explanatory comments above @Inputs and @Outputs, since these are the main elements that Storybook displays in its user interface. The @Inputs and @Outputs are elements you can interact with in Storybook, such as controls.
自动设置
¥Automatic setup
通过 npx storybook@latest init 安装 Storybook 时,你可以自动设置 Compodoc。
¥When installing Storybook via npx storybook@latest init, you can set up Compodoc automatically.
手动设置
¥Manual setup
如果你已经安装了 Storybook,则可以手动设置 Compodoc。
¥If you have already installed Storybook, you can set up Compodoc manually.
安装以下依赖:
¥Install the following dependencies:
npm install --save-dev @compodoc/compodoc将以下选项添加到你的 Storybook Builder:
¥Add the following option to your Storybook Builder:
{
"projects": {
"your-project": {
"architect": {
"storybook": {
"builder": "@storybook/angular:start-storybook",
"options": {
// 👇 Add these
"compodoc": true,
"compodocArgs": [
"-e",
"json",
"-d",
// Where to store the generated documentation. It's usually the root of your Angular project. It's not necessarily the root of your Angular Workspace!
"."
],
}
},
"build-storybook": {
"builder": "@storybook/angular:build-storybook",
"options": {
// 👇 Add these
"compodoc": true,
"compodocArgs": [
"-e",
"json",
"-d",
"."
],
}
}
}
}
}
}转到你的 .storybook/preview.ts 并添加以下内容:
¥Go to your .storybook/preview.ts and add the following:
import type { Preview } from '@storybook/angular';
// 👇 Add these
import { setCompodocJson } from '@storybook/addon-docs/angular';
import docJson from '../documentation.json';
setCompodocJson(docJson);
const preview: Preview = {};
export default preview;应用级提供程序
¥Application-wide providers
如果你的组件依赖于应用范围的提供程序,例如 BrowserAnimationsModule 定义的提供程序或任何其他使用 forRoot 模式提供 ModuleWithProviders 的模块,则可以将 applicationConfig decorator 应用于该组件的所有故事。这将为他们提供 bootstrap 应用功能,用于在 Storybook 中引导组件。
¥If your component relies on application-wide providers, like the ones defined by BrowserAnimationsModule or any other modules that use the forRoot pattern to provide a ModuleWithProviders, you can apply the applicationConfig decorator to all stories for that component. This will provide them with the bootstrapApplication function, used to bootstrap the component in Storybook.
import { Meta, applicationConfig, StoryObj } from '@storybook/angular';
import { BrowserAnimationsModule, provideAnimations } from '@angular/platform-browser/animations';
import { importProvidersFrom } from '@angular/core';
import { ChipsModule } from './angular-src/chips.module';
const meta: Meta<ChipsModule> = {
component: ChipsModule,
decorators: [
// Apply application config to all stories
applicationConfig({
// List of providers and environment providers that should be available to the root component and all its children.
providers: [
...
// Import application-wide providers from a module
importProvidersFrom(BrowserAnimationsModule)
// Or use provide-style functions if available instead, e.g.
provideAnimations()
],
}),
],
};
export default meta;
type Story = StoryObj<ChipsModule>;
export const WithCustomApplicationProvider: Story = {
render: () => ({
// Apply application config to a specific story
applicationConfig: {
// The providers will be merged with the ones defined in the applicationConfig decorator's providers array of the global meta object
providers: [...],
}
})
}Angular 依赖
¥Angular dependencies
如果你的组件依赖于其他 Angular 指令和模块,则可以使用 moduleMetadata decorator 为组件的所有故事或单个故事提供这些指令和模块。
¥If your component has dependencies on other Angular directives and modules, these can be supplied using the moduleMetadata decorator either for all stories of a component or for individual stories.
import { Meta, moduleMetadata, StoryObj } from '@storybook/angular';
import { YourComponent } from './your.component';
const meta: Meta<YourComponent> = {
component: YourComponent,
decorators: [
// Apply metadata to all stories
moduleMetadata({
// import necessary ngModules or standalone components
imports: [...],
// declare components that are used in the template
declarations: [...],
// List of providers that should be available to the root component and all its children.
providers: [...],
}),
],
};
export default meta;
type Story = StoryObj<YourComponent>;
export const Base: Story = {};
export const WithCustomProvider: Story = {
decorators: [
// Apply metadata to a specific story
moduleMetadata({
imports: [...],
declarations: [...],
providers: [...],
}),
],
};常见问题
¥FAQ
如何手动安装 Angular 框架?
¥How do I manually install the Angular framework?
安装 Angular 框架最简单的方法是运行升级命令,但你也可以手动设置。首先,安装框架:
¥The easiest way to install the Angular framework is to run the upgrade command, but you can also set it up manually. First, install the framework:
npm install --save-dev @storybook/angular然后,更新你的 .storybook/main.js|ts 以更改框架属性:
¥Then, update your .storybook/main.js|ts to change the framework property:
import { StorybookConfig } from '@storybook/angular';
const config: StorybookConfig = {
// ...
framework: '@storybook/angular', // 👈 Add this
};
export default config;最后,更新你的 angular.json 以包含 Storybook 构建器:
¥Finally, update your angular.json to include the Storybook builder:
{
"projects": {
"your-project": {
"architect": {
"storybook": {
"builder": "@storybook/angular:start-storybook",
"options": {
// The path to the storybook config directory
"configDir": ".storybook",
// The build target of your project
"browserTarget": "your-project:build",
// The port you want to start Storybook on
"port": 6006
// More options available, documented here:
// https://github.com/storybookjs/storybook/tree/next/code/frameworks/angular/src/builders/start-storybook/schema.json
}
},
"build-storybook": {
"builder": "@storybook/angular:build-storybook",
"options": {
"configDir": ".storybook",
"browserTarget": "your-project:build",
"outputDir": "dist/storybook/your-project"
// More options available, documented here:
// https://github.com/storybookjs/storybook/tree/next/code/frameworks/angular/src/builders/build-storybook/schema.json
}
}
}
}
}
}如何迁移到 Angular Storybook 构建器?
¥How do I migrate to an Angular Storybook builder?
Storybook Angular 构建器 是一种在 Angular 工作区中运行 Storybook 的方法。它是直接运行 storybook dev 和 storybook build 的替代品。
¥The Storybook Angular builder is a way to run Storybook in an Angular workspace. It is a drop-in replacement for running storybook dev and storybook build directly.
你可以运行 npx storybook@latest automigrate,让 Storybook 检测并自动修复你的配置。否则,你可以按照以下步骤手动调整配置。
¥You can run npx storybook@latest automigrate to let Storybook detect and automatically fix your configuration. Otherwise, you can follow the next steps to adjust your configuration manually.
在 Angular 工作区中使用单个项目
¥With a single project in your Angular workspace
转到你的 angular.json,并在项目的 architect 部分中添加 storybook 和 build-storybook 条目,如图 above 所示。
¥Go to your angular.json and add storybook and build-storybook entries in your project's architect section, as shown above.
然后调整 package.json 脚本部分,将现有的 Storybook 脚本替换为 Angular CLI 命令:
¥Then, adjust your package.json script section, to replace the existing Storybook scripts with the Angular CLI commands:
{
"scripts": {
- "storybook": "start-storybook -p 6006", // or `storybook dev -p 6006`
- "build-storybook": "build-storybook" // or `storybook build`
+ "storybook": "ng run <project-name:storybook",
+ "storybook": "ng run <project-name:storybook",
}
}请注意,compodoc 现在已内置于 @storybook/angular 中;你无需显式调用它。如果你在 package.json 脚本中运行了 compodoc,则可以移除相关脚本:
¥Note that compodoc is now built into @storybook/angular; you don't have to call it explicitly. If you were running compodoc in your package.json scripts, you can remove the related script:
{
"scripts": {
- "docs:json": "compodoc -p tsconfig.json -e json -d ./documentation",
- "storybook": "npm run docs:json && start-storybook -p 6006",
- "build-storybook": "npm run docs:json && build-storybook"
+ "storybook": "ng run <project-name:storybook",
+ "storybook": "ng run <project-name:storybook",
}
}在 Angular 工作区中使用多个项目
¥With multiple projects in your Angular workspace
如果你有多个项目,则必须按照上述说明,为每个要使用 Storybook 的项目调整 angular.json 和 package.json。请注意,每个项目都应该在其根目录下放置一个专用的 .storybook 文件夹。
¥In case you have multiple projects, you will have to adjust your angular.json and package.json as described above for each project you want to use Storybook with. Please note that each project should have a dedicated .storybook folder placed at the project's root directory.
你可以为每个项目依次运行 npx storybook@latest init,以便为每个项目设置 Storybook,从而自动创建 .storybook 文件夹并在 angular.json 中创建必要的配置。
¥You can run npx storybook@latest init sequentially for each project to set up Storybook for each of them to automatically create the .storybook folder and create the necessary configuration in your angular.json.
然后,你可以将多个 Storybook 与 Storybook 组合 组合使用。
¥You can then combine multiple Storybooks with Storybook composition.
如何为 Storybook 配置 Angular 的构建器?
¥How do I configure Angular's builder for Storybook?
这些是 Angular 构建器可能需要的常用选项:
¥These are common options you may need for the Angular builder:
| 配置元素 | 描述 |
|---|---|
"browserTarget" | 使用以下格式构建要提供的目标。"example-project:builder:config" |
"debugWebpack" | 调试 Webpack 配置 "debugWebpack": true |
"tsConfig" | TypeScript 配置文件相对于当前工作区的位置。"tsConfig": "./tsconfig.json". |
"preserveSymlinks" | 解析模块时请勿使用真实路径。如果为 true,则符号链接将解析为其真实路径;否则,它们将被解析为其符号链接路径。"preserveSymlinks": true |
"port" | Storybook 使用的端口。"port": 6006 |
"host" | 为 Storybook 设置自定义主机。"host": "http://my-custom-host" |
"configDir" | Storybook 配置目录位置。"configDir": ".storybook" |
"https" | 在启用 HTTPS 的情况下启动 Storybook。"https": true 需要自定义证书信息。 |
"sslCa" | 提供 SSL 证书颁发机构。"sslCa": "your-custom-certificate-authority" 可选与 "https" 一起使用 |
"sslCert" | 提供 SSL 证书。"sslCert": "your-custom-certificate" https 必需 |
"sslKey" | 提供 SSL 密钥来为 Storybook 提供服务。"sslKey": "your-ssl-key" |
"smokeTest" | 成功启动后退出 Storybook。"smokeTest": true |
"ci" | 以 CI 模式启动 Storybook(跳过交互式提示并且不会打开浏览器窗口)。"ci": true |
"open" | 是否在浏览器中自动打开 Storybook。"open": true |
"quiet" | 过滤 Storybook 详细构建输出。"quiet": true |
"enableProdMode" | 禁用 Angular 的开发模式,该模式会关闭框架内的断言和其他检查。"enableProdMode": true |
"docs" | 在 文档模式 中启动 Storybook。"docs": true |
"compodoc" | 之前执行 compodoc。"compodoc": true |
"compodocArgs" | Compodoc options。始终提供选项 -p 和 -d,其中 -p 表示 tsconfig 路径,-d 表示工作区根目录。"compodocArgs": ["-e", "json"] |
"styles" | 提供与 Storybook 一起使用的 应用的样式 的位置。"styles": ["src/styles.css", "src/styles.scss"] |
"stylePreprocessorOptions" | 为解析到工作区根目录的样式预处理器提供进一步的自定义。"stylePreprocessorOptions": { "includePaths": ["src/styles"] } |
"assets" | 静态应用资源列表。"assets": ["src/assets"] |
"initialPath" | 首次访问 Storybook 时要附加的 URL 路径。"initialPath": "docs/configure-your-project--docs" |
"webpackStatsJson" | 将 Webpack Stats JSON 写入磁盘。"webpackStatsJson": true |
"previewUrl" | 禁用默认的故事书预览,并允许你使用自己的预览。"previewUrl": "iframe.html" |
"loglevel" | 构建期间控制日志记录的级别。可以是以下之一:[silly、verbose、info(默认)、warn、error、silent]。"loglevel": "info" |
"sourceMap" | 配置 sourcemaps。"sourceMap": true |
"experimentalZoneless" | 配置 无区域变更检测。"experimentalZoneless": true |
完整的选项列表可以在 Angular 构建器模式中找到:
¥The full list of options can be found in the Angular builder schemas:
API
选项
¥Options
如果需要,你可以传递一个选项对象以进行其他配置:
¥You can pass an options object for additional configuration if needed:
import type { StorybookConfig } from '@storybook/angular';
const config: StorybookConfig = {
framework: {
name: '@storybook/angular',
options: {
// ...
},
},
};可用选项包括:
¥The available options are:
builder
类型:Record<string, any>
¥Type: Record<string, any>
配置 框架的构建器 的选项。对于此框架,可以在 Webpack 构建器文档 中找到可用选项。
¥Configure options for the framework's builder. For this framework, available options can be found in the Webpack builder docs.
