Project/Figma+Storybook

1. 디자인시스템 - Rollup을 사용하여 Storybook npm 배포 및 사용

건담아빠 2023. 11. 10. 10:27

 

이번분기 최대 목표는 디자인 시스템을 어떻게 만들것이가?

개발 및 디자인팀과의 협업을 어떻게 할것인가에 대한 프로토타입 정도가 목적임으로 방향을성을 찾기위한 테스트 정도록만 작업하도록 해보겠다.

 

작업방향 및 고려사항

  • npm에 올려 사용할 목적임으로 번들을 최소화 (Create React App 미사용)
  • Storybook을 컴포넌트 관리  chromatic 사용 검토 (Storybook 전용 서버 검토)
  • TypeScript 기반의 React 개발환경 구축 및 TypeScript가 아닌것도 사용 가능하도록
  • Atomic 하게 만들되 각 프로젝트에서는 어떤식으로 사용할 것인가
  • Page별 Component들은 어떤식으로 관리할 것인가?
  • Figma에서 수작업이 아닌 자동으로 컴포넌트를 쉽게 가져올수 있는 방법
  • css 관리는 어떤식으로 하는게 좋을까 (SCSS ?)
  • storybook 및 react 버전이 프로젝트 버전이랑 차이나는 부분은?

 

구성도

 

1. 프로젝트 생성

yarn init 을 통하여 기본 package.json 생성 (--yes / -y 옵션은 대화형 세션을 건너뛰고 package.json 기본값을 기반으로 생성)

# 프로젝트 폴더 생성 및 폴더이동
$ mkdir react-storybook-rollup-starter
$ cd react-storybook-rollup-starter

# 대화형 세션을 건너뛰고 package.json 기본값을 기반으로 생성
$ yarn init -y

# src 폴더가 소스코드의 최상위 폴더
$ mkdir src

 

2. React 설치

React 관련 라이브러리를 설치하고, 라이브러리 구동에 직접적 연관이 없는 라이브러리들은 --dev / -D 옵션을 지정하여 devDependencies에 추가한다.

2.1 React 및 TypeScript 설치

$ yarn add -D react react-dom @types/react typescript
OR
$ yarn add --dev react react-dom @types/react typescript

package.json에 아래코드 추가

...
"peerDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
},
...

 

2.2. tsconfig.json 생성 및 설정

tsconfig.json 파일을 생성하고 설정한다.

$ vi tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "outDir": "dist",
    "lib": ["dom", "dom.iterable", "esnext"],
    "declaration": true,
    "declarationDir": "dist",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

 

3. Storybook 설치

3.1. Storybook을 설치

필자는 webpack5 선택

$ npx sb init

 

3.2. 설정확인

# .storybook/main.ts

...
"stories": [
    "../src/**/*.stories.tsx"
 ],
...

 

3.3. 설치 후 실행

$ yarn storybook

const stringWidth = require('string-width') 에러가 발생하였다. (해결방법)

필자는 yarn cache를 모두 지워주고, npm 및 yarn을 최신버전으로 업데이트하고 라이브러리를 다시 설치하였다.

 

3.4. 내보내는 항목파일 만들기

# src/index.ts

import { Button } from "./stories/Button";
export { Button };

 

4. Rollup.js 빌더 설치

4.1. rollup.js 빌더 관련 라이브러리 설치

$ yarn add --dev rollup @rollup/plugin-typescript @rollup/plugin-commonjs @rollup/plugin-node-resolve rollup-plugin-peer-deps-external rollup-plugin-postcss rollup-plugin-dts postcss

 

아래 에러 발생해서 node version 변경해 줬다. (변경방법)

error rollup@4.3.0: The engine "node" is incompatible with this module. Expected version ">=18.0.0". Got "14.17.4"

$ nvm ls
$ nvm use 20.9.0

 

4.2. package.json에 모듈 진입점 설정

# package.json

...
    "main": "dist/index.js",
    "module": "dist/index.esm.js",
    "types": "dist/index.d.ts",
...

 

4.3. rollup.config.mjs 생성 및 설정

$ vi rollup.config.mjs
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import postcss from "rollup-plugin-postcss";
import dts from "rollup-plugin-dts";

// This is required to read package.json file when
// using Native ES modules in Node.js
// https://rollupjs.org/command-line-interface/#importing-package-json
import { createRequire } from 'node:module';
const requireFile = createRequire(import.meta.url);
const packageJson = requireFile('./package.json');


export default [{
  input: "src/index.ts",
  output: [
    {
      file: packageJson.main,
      format: "cjs",
      sourcemap: true
    },
    {
      file: packageJson.module,
      format: "esm",
      sourcemap: true
    }
  ],
  plugins: [
    peerDepsExternal(),
    resolve(),
    commonjs(),
    typescript(),
    postcss({
      extensions: ['.css']
    })
  ]
}, {
  input: 'dist/index.d.ts',
  output: [{ file: 'dist/index.d.ts', format: 'es' }],
  plugins: [dts()],
  external: [/\.css$/]
}];

 

4.4. 빌드스크립트 추가

# package.json

...
    "scripts": {
        ...
        "build": "rollup -c"
    },
...

 

4.5. 빌드 테스트

$ yarn build

 

4.6. 타입 에러 (const meta = {)

Button.stories.ts 등의 cont meta 부분에 타입을 지정해준다.

const meta: Meta<typeof Button> = {

 

5. 프로젝트 설정

5.1. .npmignore 설정

$ vi .npmignore
.storybook/
src/
.github/
./storybook
rollup.config.mjs
tsconfig.json
yarn.lock

 

6. NPM / YARN 배포

6.1. 로그인

$ npm login

 

6.2. package.json 설정 확인

@djgundam/react-storybook-rollup-starter 아래에 1.0.0 버전으로 배포하기 위해서 name 및 version을 변경해 준다.

{
    "name": "@djgundam/react-storybook-rollup-starter",
    "version": "1.0.12",
  ...
  
}

 

6.3. 출시

package.json

    ...
    "scripts": {
        "build-publish": "yarn build && yarn publish --access public"
    },
    ...
$ yarn publish --access public
OR
$ yarn build-publish

 

6.4. 추가 설정 (선택)

npm 서버에 푸시할 패키지 지정

예: dist 패키지 및 test.ts 만 npm 서버에 푸시 (단 .npmignore에 test.ts가 설정되었다면 제외된다.)

    ...
    "files": [
        "dist",
        "test.ts"
    ]
    ...

 

6.5. 배포확인

npmjs.com에서 확인이 가능하다.

 

7. 확인

7.1. 리액트 설치

$ npx create-react-app design-system-test-app --template typescript
$ yarn create react-app design-system-test-app --template typescript

 

7.2. npm 라이브러리 설치

$ yarn add @djgundam/react-storybook-rollup-starter

 

7.3. 확인

import { Button } from '@djgundam/test11111'

...
	<Button label="121212" primary/>
...

 

 

 

참고

https://prateeksurana.me/blog/react-component-library-using-storybook-7/

 

Creating a React component library using Storybook 7

Learn how to build a React component library using Storybook 7 and TypeScript, compile it with Rollup and publish it.

prateeksurana.me

https://www.codefeetime.com/post/rollup-config-for-react-component-library-with-typescript-scss/

 

Rollup Config for React Component Library With TypeScript + SCSS

Introduction In this article, I will try to cover the main areas that are crucial in making the Rollup configurations work in building a React component library, with TypeScript and SCSS in particular. At the same time, I will put down some notes for the v

www.codefeetime.com

https://blog.itcode.dev/projects/2022/06/10/react-components-library-starter#%EB%AA%A9%ED%91%9C

 

Rollup.js로 React 컴포넌트 라이브러리 개발기 - 𝝅번째 알파카의 개발 낙서장

회사에서 할당받은 업무 중 하나로, 컴포넌트를 라이브러리화하여 npm으로 배포하는 업무를 맡게 됐다. 즉, react-bootstrap 같은 컴포넌트 라이브러리를 개발해야한다. 코드 배포 경험이라곤 예전에

blog.itcode.dev

https://blog.itcode.dev/projects/2022/06/10/react-components-library-starter

https://velog.io/@velopert/bundle-with-rollup-and-publish-to-npm#5-1-rollup%EC%9C%BC%EB%A1%9C-%EB%9D%BC%EC%9D%B4%EB%B8%8C%EB%9F%AC%EB%A6%AC-%EB%B2%88%EB%93%A4%ED%95%98%EA%B8%B0

https://flamingotiger.github.io/frontend/DevEnv/rollup-setup/

https://velog.io/@sunohvoiin/JavaScript-Tree-Shaking