[번역] Astrobook: 프레임워크를 가리지 않는 가벼운 UI 컴포넌트 플레이그라운드

링크 · github.comGitHub - ocavue/astrobook: Minimal Storybook alternativeMinimal Storybook alternative. Contribute to ocavue/astrobook development by creating an account on GitHub.https://github.com/ocavue/astrobook

Astrobook은 어떤 도구일까?

Storybook처럼 컴포넌트를 앱 전체와 분리해서 확인하고 싶은데, 설정이 무겁게 느껴질 때가 있다. Astrobook은 이런 상황을 위해 만들어진 가벼운 UI 컴포넌트 플레이그라운드다. Astro 위에서 동작하며 React, Vue, Preact, Svelte, Solid, Lit, Astro 컴포넌트를 한 곳에서 개발하고 테스트하고 보여줄 수 있다.

이 글은 Astrobook의 GitHub README를 한국어로 옮기고 정리한 글이다. 원문은 MIT 라이선스로 공개되어 있다.

어떻게 시작할까?

README는 React를 예로 들지만, 다른 프레임워크도 Astro 공식 통합을 설치하면 같은 방식으로 사용할 수 있다.

우선 패키지를 설치한다.

npm install astro @astrojs/react astrobook

다음으로 astro.config.mjs에 astrobook 통합을 추가한다.

// astro.config.mjs
import react from '@astrojs/react'
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'

export default defineConfig({
  integrations: [react(), astrobook()],
})

package.json에는 Astro 기본 스크립트를 추가하고, 빌드 결과물인 dist/와 생성된 타입 폴더인 .astro/는 .gitignore에 추가한다.

"scripts": {
  "dev": "astro dev",
  "build": "astro build",
  "preview": "astro preview"
}

마지막으로 스토리 파일을 작성한다. Astrobook은 .stories.ts, .stories.tsx, .stories.js, .stories.jsx, .stories.mts, .stories.mjs 파일을 모두 찾아 사이드바에 보여준다. 각 파일에는 필수인 default export와 하나 이상의 named export가 있어야 한다.

// src/components/Button.stories.ts
import { Button, type ButtonProps } from './Button.tsx'

export default {
  component: Button,
}

export const PrimaryButton = {
  args: { variant: 'primary' } satisfies ButtonProps,
}

export const SecondaryButton = {
  args: { variant: 'secondary' } satisfies ButtonProps,
}

npm run dev를 실행하고 http://localhost:4321에 접속하면 작성한 스토리를 확인할 수 있다.

Storybook의 Component Story Format v3를 모두 지원하는 것은 아니고 일부만 호환된다. 특히 args와 decorators 속성을 지원한다.

Decorators로 컴포넌트를 감싸려면?

Decorator는 컴포넌트와 그 컴포넌트에 전달할 props를 담은 객체다. 렌더링할 때 자식 요소를 넣을 slot이 있어야 한다. 현재는 스타일 변경만 지원하고, 컴포넌트의 컨텍스트나 클라이언트 측 동작은 바꿀 수 없다. Decorator는 Astro가 HTML로 렌더링해서 클라이언트로 보낸다.

예를 들어 컴포넌트에 초록색 테두리를 두르는 React decorator와 빨간색 테두리를 두르는 Astro decorator를 만들 수 있다.

// ReactGreenBorderDecorator.tsx
import type { ComponentChildren } from 'react'

export function GreenBorderDecorator({
  width = 2,
  children,
}: {
  width?: number
  children?: ComponentChildren
}) {
  return <div style={{ border: `solid ${width}px green` }}>{children}</div>
}
<!-- AstroRedBorderDecorator.astro -->
<div style="border: solid 2px red;">
  <slot />
</div>

스토리에서는 decorators 배열에 넣어 사용한다. 아래 예시는 버튼을 빨간 테두리로 감싼 뒤, 그 바깥을 다시 초록 테두리로 감싼다.

// Button.stories.tsx
import RedBorderDecorator from './AstroRedBorderDecorator.astro'
import { Button, type ButtonProps } from './Button.tsx'
import { GreenBorderDecorator } from './ReactGreenBorderDecorator.tsx'

export default {
  component: Button,
}

export const PrimaryButton = {
  args: { variant: 'primary' } satisfies ButtonProps,
  decorators: [
    { component: GreenBorderDecorator, props: { width: 10 } },
    { component: RedBorderDecorator },
  ],
}

스토리가 하나뿐이면 사이드바는 어떻게 보일까?

모듈 이름과 같은 이름의 스토리가 해당 모듈의 유일한 스토리라면, 자동으로 부모 컴포넌트 자리까지 끌어올려진다(single-story hoisting). 사이드바에 Button/Button처럼 같은 이름이 중복해서 중첩되는 것을 막아준다.

// Button.stories.ts
import { Button as ButtonComponent } from './Button.tsx'

export default {
  component: ButtonComponent,
}

// named export가 하나뿐이고, 이름이 모듈 이름(Button.stories.ts)과 같다.
export const Button = {}

이 스토리는 UI에서 Button/Button으로 중첩되지 않고 Button으로만 표시된다.

어떤 옵션을 설정할 수 있을까?

astrobook() 통합에는 다음 옵션을 넘길 수 있다.

  • directory: 스토리를 찾을 디렉터리다. 기본값은 현재 작업 디렉터리이고, 'src/components'처럼 지정할 수 있다.
  • subpath: Astrobook을 독립 앱으로 실행할 수도 있지만, 기존 Astro 프로젝트에 붙일 때는 subpath로 하위 경로를 정한다. '/playground'를 지정하면 http://localhost:4321/playground에서 열린다. 이 값은 Astro의 base 경로를 기준으로 하므로, base가 '/docs'라면 /docs/playground에서 열린다.
  • css: Astrobook 사이트에 가져올 CSS 파일 경로 배열이다. 스타일을 커스터마이징할 때 사용한다.
  • head: 사이트의 head에 넣을 커스텀 태그를 담은 Astro 컴포넌트 경로다. 폰트 로드나 전역 스타일처럼 link, style, script 등 head 안에 허용되는 요소만 넣어야 한다.
  • home: 대시보드 홈 화면을 대체할 Astro 컴포넌트 경로다.
  • homeContent: 기본 홈 화면을 통째로 바꾸지 않고 내용만 조정한다. title, subtitle, version 배지, repo 배지를 지정하거나 false로 숨길 수 있다. home을 직접 지정했거나 home: false라면 이 옵션은 무시된다.
  • title: 사이트 제목이다.
// astro.config.mjs
import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'

export default defineConfig({
  integrations: [
    astrobook({
      directory: 'src/components',
      subpath: '/playground',
      title: 'My Components Playground',
      css: ['./src/styles/custom.css'],
    }),
  ],
})

개발 환경에서만 켜고 싶다면?

기존 Astro 프로젝트에 Astrobook을 붙이되 프로덕션 빌드에는 포함하고 싶지 않다면, process.env.NODE_ENV로 통합을 조건부로 넣으면 된다. 아래 설정에서는 개발 중에만 http://localhost:4321/astrobook에서 Astrobook을 사용할 수 있다.

import { defineConfig } from 'astro/config'
import astrobook from 'astrobook'

export default defineConfig({
  integrations: [
    process.env.NODE_ENV === 'development'
      ? astrobook({ subpath: '/astrobook' })
      : null,
  ],
})

Astrobook을 iframe 안에서 실행한다면 메시지로 테마를 전환할 수도 있다.

const theme = 'light' // or 'dark'
iframe.contentWindow.postMessage({ type: 'astrobook:set-theme', theme }, '*')

글을 마치며

Astrobook은 여러 프레임워크의 컴포넌트를 하나의 카탈로그에 담을 수 있고, 설정이 Astro 통합 하나로 끝난다는 점이 특징이다. 다만 Storybook의 CSF3를 일부만 지원하고, decorator도 스타일 변경에 한정된다는 점은 도입 전에 확인해야 한다. 이미 Storybook의 애드온이나 인터랙션 테스트에 의존하고 있다면 대체재로 보기는 어려울 수 있고, 컴포넌트를 빠르게 모아 보여주는 용도라면 살펴볼 만하다.

참고 자료

댓글을 불러오는 중…