스토리북 설정하기
작성일 : 2023.01.03 / 수정일 : 2023.01.05
들어가며
이번 장은 스토리북 및 스토리 설정에 대해 작성한다.
주의! 해당 글에 작성된 내용은 v6.5를 기준으로 작성하였습니다.
2023.01 일자 기준으로 최신버전은 7.0(beta)가 릴리즈 되었음.
설치 시 오류가 너무 잦다.
1. 스토리란?
랜더링 된 UI 컴포넌트를 캡처한 것으로 다음과 같이 작성할 수 있다.
구성 요소의 스토리는 구성 요소 파일과 함께 있는 스토리 파일에 정의된다.
스토리 파일은 개발 전용이며 프로덕션 번들에 포함되지 않음.
// Button.stories.js|jsx|ts|tsx // 파일명
import React from 'react'; // 리액트 사용
import { ComponentStory, ComponentMeta } from '@storybook/react';
import { Button } from './Button'; // 버튼 컴포넌트 가져옴
// 스토리의 default 값 설정
export default {
title: 'Button', // 스토리명
component: Button, // 스토리로 사용될 컴포넌트
decorators: [...] // 스토리를 감쌀 wraper 설정
parameters: {...} // 스토리 전역에 사용될 parameters 설정
argTypes: {...} // 스토리 전역에 사용될 args manual 설정
includeStories: [...] // 생성한 스토리 중 스토리북 실행 시 보여줄 리스트 설정
excludeStories: [...] // 생성한 스토리 중 스토리북 실행 시 제외할 리스트 설정
} as ComponentMeta<typeof Button>; // 컴포넌트로 args의 타입 추론
// 스토리에 사용될 공통 템플릿 설정 (함수형 컴포넌트라고 생각하면 편하다)
const Template: ComponentStory<typeof Button> = (args) => <Button {...args} />;
// 템플릿을 복사한 스토리 생성
export const Primary = Template.bind({});
// Primary 스토리에 대한 args 설정, 컴포넌트의 props 설정 관련
Primary.args = {
primary: true, // primary props에 대한 값 설정
label: 'Button', // label props에 대한 값 설정
};
// Primary 스토리에 대한 parameters 설정, 에드온 및 스토리북 설정과 관련
Primary.parameters = {
controls: {
sort: "requiredFirst", // props 중 필수값 먼저 정렬
include: [ // 해당 props만 포함
"label",
"onClick",
],
}
actions: {...}
};
2. 스토리북 주요 옵션
주의. 모든 옵션을 설명하지 않음 더 다양한 옵션에 대한 내용은 공식문서를 참조해 주세요.
참고링크
1. args
args, argTypes는 컴포넌트의 props를 기반으로 한 Control 패널의 제어 수단이다.
args === props 로 생각하면 편함.
...
const Template: ComponentStory<typeof All> = (args) => {
return <Button {...args} />
}
- 이 때 args는 컴포넌트가 가질 수 있는 모든 props를 포함함.
- props의 defaultValue가 설정되었을 경우 해당 props가 적용됨.
- 값 우선순위 : 스토리 설정 > 컴포넌트 설정 > preview.js 설정 > 컴포넌트 기본 값
a. 개별 스토리의 args 설정하기
개별적인 스토리의 args(props) 값을 변경하고 싶다면 스토리.args 로 접근하여 설정.
설정하지 않은 args는 상위 값을 따라 설정됨.
...
const Template: ComponentStory<typeof Button> = (args) => {
return (
<Button {...args} />
)
}
export const Primary = Template.bind({}) // Template을 복사해서 생성한 스토리1
Primary.args = {
color: "pri" // 스토리1의 color를 'pri'로 설정
...
}
export const Secondary = Template.bind({}) // Template을 복사해서 생성한 스토리2
Secondary.args = {
color: "sec" // 스토리2의 color를 'sec'로 설정
...
}
b. 컴포넌트의 args 설정하기
default의 args 를 추가하여 설정. 설정하지 않은 args는 상위 값을 따라 설정됨.
const buttonArgs = {color : "red"} // 컴포넌트 전역에 사용될 args
export default {
title: "Components/Button",
component: All,
args : buttonArgs // args 설정
excludeStories: ["All"],
} as ComponentMeta<typeof Button>
const Template: ComponentStory<typeof Button> = (args) => {
return (
<Button {...args} />
)
}
export const Primary = Template.bind({}) // color : "red"
export const Secondary = Template.bind({}) // color : "red"
c. 스토리북 전역 args 설정하기
preview.js 에 args 선언 후 export해서 해당 값 설정.
설정하지 않은 args는 상위 값을 따라 설정됨.
export const args = { theme: "light" } // 모든 스토리북의 theme : "light"
참고링크
2. argTypes
argTypes는 args의 고급설정이다.
Controls 패널에 출력되는 Control, Docs 탭에 출력되는 table을 제어할 수 있음.
const buttonArgTypes = {
// args.buttonName의 대한 설정
buttonName: {
control: "text", // Control의 타입 설정
defaultValue: "ACTION", //Control의 설정되는 defaultValue
name : "buttonName", // Control 탭의 Name 설정
description : "buttonName OK?" // Docs 탭의 Description 설정(ts의 /** */설정 대응)
table : {
type : {summary : "string"}, // Docs 탭의 Description 요약 설정(ts의 type설정 대응)
defaultValue : { summary : "HELLO"} // Docs 탭의 Default 설정
}
},
// args.onClick의 대한 설정
onClick: { control: false },
}
참고링크
3. parameters
스토리북의 기능 및 애드온 동작의 제어수단. ex) action 설정
a. 개별 스토리의 parameters 설정하기
개별적인 스토리의 parameters 값을 변경하고 싶다면 스토리.args 로 접근하여 설정.
설정하지 않은 args는 상위 값을 따라 설정됨.
const Template: ComponentStory<typeof Button> = (args) => {
return (
<Button {...args} />
)
}
export const Primary = Template.bind({}) // Template을 복사해서 생성한 스토리1
Primary.parameters = {
{controls : {incldue : ["color"]} // color controls만 출력
...
}
export const Secondary = Template.bind({}) // Template을 복사해서 생성한 스토리2
Secondary.parameters = {
{controls : {incldue : ["variant"]} // variant controls만 출력
...
}
b. 컴포넌트의 parameters 설정하기
default의 parameters 를 추가하여 설정.
설정하지 않은 args는 상위 값을 따라 설정됨.
const buttonParameters = {controls : {incldue : ["color"]} // 컴포넌트 전역에 사용될 parameters
export default {
title: "Components/Button",
component: All,
parameters : buttonArgs // parameters 설정
excludeStories: ["All"],
} as ComponentMeta<typeof Button>
const Template: ComponentStory<typeof Button> = (args) => {
return (
<Button {...args} />
)
}
export const Primary = Template.bind({}) // color controls만 출력
export const Secondary = Template.bind({}) // color controls만 출력
c. 스토리북 전역 parameters 설정하기
preview.js 에 parameters 선언 후 export해서 해당 값 설정.
설정하지 않은 args는 상위 값을 따라 설정됨.
export const parameters = { actions: { argTypesRegex: "^on[A-Z].*" } } // 모든 스토리북의 on으로 시작되는 control action 출력
참고링크
4. decorators
(컴포넌트|스토리)를 감쌀 요소를 작성할 수 있는 옵션.
import { ComponentMeta } from "@storybook/react"
import { YourComponent } from "./YourComponent"
export default {
title: "YourComponent",
component: YourComponent,
// decorators 추가
decorators: [
(Story) => (
<div style={{ margin: "3em" }}>
{" "}
// component wrapper 설정
<Story /> // 실제 컴포넌트
</div>
),
],
} as ComponentMeta<typeof YourComponent>
참고링크
3. 애드온
스토리북 사용을 도와주는 플러그인.
1. 애드온 설치 및 설정하기
애드온 설치 후 .storybook/main.js 의 addons 배열에 추가
npm install 추가애드온 -D --force // 애드온 설치
// .storybook/main.js
module.exports = {
...
addons : [
"@storybook/addon-links",
"@storybook/addon-essentials",
"@storybook/addon-interactions",
"설치한 애드온 추가"
],
...
}
2. 필수 애드온
스토리북 설치 시 함께 설치되는 애드온.
- @storybook/addon-essentials
- Actions // action 애드온
- Viewport // 반응형 레이아웃 설정 애드온
- Docs // 독스 탭 애드온
- Controls // 컨트롤 탭 애드온
- Backgrounds // 배경 색 설정 애드온
- Toolbars // preview의 탭바 애드온
- @storybook/addon-links // 클릭 시 해당 스토리로 이동시키게 해주는 애드온
- @storybook/addon-interactions // play function을 사용하게 해주는 애드온
참고링크
- Essentials
- Action : 읽어보자
- Controls : 읽어보자
3. 사용 추천 애드온
module.exports = {
addons : [
"@storybook/preset-scss", // 스토리북 내에서 scss 사용 하게 해줌
"@storybook/addon-a11y", // 스토리 별 접근성 테스트 결과 제공
"storybook-addon-pseudo-states", // :active, :hover 와 같은 가상선택자 상태 뷰 제공
],
...
}
마치며
스토리북을 사용하면서 정리했던 스토리북 관련 설정을 정리해봤다.
스토리북은.. 잘 관리하는게 어려운 것 같다. 내가 못하는게 크기도 하지만..
그래도 컴포넌트 관리에 있어 정말 유용한 툴임에는 틀림없다! 잘 활용해서 좋은 디자인 시스템을 만드는데 도움이 되면 좋겠다.