AngularでStorybookを導入する
はじめに
storybookが良いと聞く今日このごろ。
Angularでも使えることを知ったので、今回はそれを試してみる。
TL;DR.
Angularプロジェクト作成
CLIでサクッと作成する。
$ ng new ng-component
Storybook導入
公式サイトに手順があるので、それを参考に進める。
これだけでセットアップが完了する。
$ npx -p @storybook/cli sb init --type angular
サンプルプログラムを追加してくれるが、
パッケージがなくうまく動かなかったりしたのでstoryを作っていく。
Storyを作成する
src/stories
配下にbutton.component.stories.ts(任意)
を作成する。
※ButtonComponent
の中身は後述
import { ButtonComponent } from '../app/component/button/button.component'; export default { title: 'button component', }; export const ButtonDefault = () => ({ component: ButtonComponent, props: { text: 'default' } });
作成したcomponent
button.component.ts
import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-button', templateUrl: './button.component.html', styleUrls: ['./button.component.scss'] }) export class ButtonComponent implements OnInit { @Input() text: string; buttonClasses: string[] = ['button']; ngOnInit() { } }
button.component.scss
.button { width: 150px; height: 50px; background-color: #fff; border: 1px solid #000; color: #333; font-size: 16px; }
button.component.html
<button [ngClass]="buttonClasses">{{text}}</button>
実行してみる
自動で追加されたnpm script
があるので、それを実行すればOK。
$ npm run storybook > ブラウザが勝手に立ち上がり表示される
画像の様に出てくれば完了。
まとめ
今回は前々からやろうと思ってたstorybookの導入をやった。
component単位で見れるものがあるのは、やっぱり楽だと思うので今後は作っていきたいところ。
+github pagesで見れると楽なのでいつか対応したい。