Angular 7, Storybook 4系
まずはng new
する。
$ ng new hoge --createApplication=false --style=scss
$ cd hoge
storybook用のproject作る。
$ ng g app storybook --minimal --skipTests --style=scss --routing=false --prefix=sb
storybookの例のアレをする。
$ npx -p @storybook/cli sb init
吐かれた設定たちをいじる。
.storybook/config.js
import { configure } from "@storybook/angular";
// automatically import all files ending in *.stories.ts
const req = require.context(
"../projects/storybook/src/stories",
true,
/.stories.ts$/
);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
.storybook/tsconfig.json
{
"extends": "../projects/storybook/tsconfig.app.json",
"compilerOptions": {
"types": ["node"]
},
"exclude": [
"../src/test.ts",
"../src/**/*.spec.ts",
"../projects/**/*.spec.ts"
],
"include": ["../src/**/*", "../projects/**/*"]
}
適当にlibrary用のproject作る。
$ ng g lib my-ui --prefix=myui
watchする。
$ ng build my-ui --watch
なんかコンポーネント作ってみる。
$ ng g component projects/my-ui/src/lib/button --export=true
projects/my-ui/src/lib/button/button.component.html
<ng-content></ng-content>
projects/my-ui/src/lib/button/button.component.scss
:host {
border: 1px solid #ddd;
border-radius: 3px;
padding: 5px;
color: #999;
}
story作る
$ mkdir -p projects/storybook/src/stories/button-stories
$ touch projects/storybook/src/stories/button-stories/button.stories.ts
$ ng g component projects/storybook/src/stories/button-stories/button-story --skipImport
projects/storybook/src/stories/button-stories/button-story/button-story.component.html
<div>
<myui-button (click)="log('hello 1')">hello 1!</myui-button>
<myui-button (click)="log('hello 2')">hello 2!</myui-button>
<myui-button (click)="log('hello 3')">hello 3!</myui-button>
<myui-button (click)="log('hello 4')">hello 4!</myui-button>
</div>
projects/storybook/src/stories/button-stories/button-story/button-story.component.ts
import { Component, OnInit } from "@angular/core";
import { action } from "@storybook/addon-actions";
@Component({
selector: "sb-button-story",
templateUrl: "./button-story.component.html",
styleUrls: ["./button-story.component.scss"]
})
export class ButtonStoryComponent implements OnInit {
log = action("click");
constructor() {}
ngOnInit() {}
}
projects/storybook/src/stories/button-stories/button.stories.ts
import { storiesOf, moduleMetadata } from "@storybook/angular";
import { MyUiModule } from "my-ui";
import { ButtonStoryComponent } from "./button-story/button-story.component";
storiesOf("Button", module)
.addDecorator(
moduleMetadata({
imports: [MyUiModule]
})
)
.add("button", () => ({
component: ButtonStoryComponent
});
storybook起動する。
$ npm run storybook
- Storybookはangular.jsonのdefaultProjectからprojectの情報を読み取る
- 対象projectのsrc/styles.scssでiframe内のglobalなスタイルを変更できる
- わちゃわちゃしてきたらSharedModuleを作ったほうがよいかも
- Router依存しているやつがいる場合はRouterTestingModuleとか突っ込んでおくととりあえず黙る