페블_
반짝이는 시냅스
페블_
전체 방문자
오늘
어제
  • 전체글 보기 (96)
    • QA (0)
    • 프로젝트 회고 (4)
    • 프로젝트 과정 기록 (12)
    • UI 구현 연구일지 (8)
    • Front-end (31)
      • Javascript (7)
      • CSS (10)
      • React (5)
      • Typescript (3)
      • Nextjs (3)
      • 스타일링 라이브러리 (3)
    • Back-end (0)
      • Express (0)
      • DB (0)
    • CS (0)
      • 자료구조 & 알고리즘 (0)
    • CI&CD (1)
    • 툴 사용법 (4)
      • Git (1)
      • Library&패키지 (2)
      • 기타 개발관련 (1)
    • 알고리즘 이론 & 풀이 (36)
      • 백준(BOJ) (14)
      • 프로그래머스 (22)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 캐러셀
  • 생각
  • 시리즈_표지
  • react
  • chartjs
  • UI 컴포넌트
  • 토이프로젝트
  • emotion
  • Python
  • eslint
  • JS
  • 파이썬
  • 개발블로그_시작
  • storybook
  • 알고리즘
  • TypeScript
  • 선형대수학
  • 백준

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
페블_

반짝이는 시냅스

Front-end/스타일링 라이브러리

Typescript + Emotion + Storybook 설치 및 환경설정

2023. 6. 19. 16:56

react typescript 프로젝트 생성 및 emotion 설치

npx create-react-app [만들 프로젝트 경로] --template typescript
npm install @emotion/react

React가 v17 이후에 emotion을 사용하려면 다음과 같은 pragma를 앞에 입력해줘야 한다.

/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";

 

npm install @emotion/react

이건 css prop 방식이고 만약 styled 방식도 사용하고 싶다면

npm install @emotion/styled

도 설치하기

emotion pragma 제거 방법

React 자체의 jsx가 아니라 emotion의 jsx 해석 방법을 사용한다는 의미로 맨 앞에 이런 prgama를 입력해야 한다.

/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";

제거하는 방법은 바벨 설정을 건드리는 것인데 CRA로 만든 프로젝트에서는 eject(숨겨진 웹팩 설정 파일들을 보이게 하는 것)을 하면 되돌릴 수 없기 때문에 eject 하지 않고도 설정을 건드릴 수 있는 craco라는 패키지의 도움을 받을 것이다.

 

1. tsconfig.json 파일 설정

아래와 같이 "jsxImportSource": "@emotion/react" 을 한 줄 추가해준다. 그러면 ts 컴파일러가 pragma를 제거해도 css props에 빨간줄을 띄우지 않는다. 하지만 이건 ts 컴파일러 부분만 해결한 것이기 때문에 정말로 jsxImportSource를 하게 하려면 웹팩 설정을 해줘야 한다.

{
  "compilerOptions": {
  	...,
    "jsxImportSource": "@emotion/react"
   }
}

 

2. craco와 emotion-babel-preset 패키지 설치

npm install @craco/craco
npm instsall @emotion/babel-preset-css-prop

 

craco는 웹팩 설정을 하는데 도움을 주는 패키지이고, @emotion/babel-preset-css-prop은 emotion의 css props의 사용을 바벨이 이해할 수 있게 해주는 설정 파일이다.

 

3. craco.config.js

프로젝트의 루트 디렉토리 아래에 craco.config.js 라는 이름으로 파일을 생성하고 다음과 같이 입력한다.

module.exports = {
    babel: { presets: ['@emotion/babel-preset-css-prop'] },
}

 

4. package.json의 scripts 수정

craco가 start와 build 등을 실행할 수 있게 다음과 같이 바꾼다.

storybook은 그냥 냅두기

"scripts" : {
   "start": "craco start", 
   "build": "craco build", 
   "test": "craco test",
   ...,
    "storybook": "storybook dev -p 6006",
    "build-storybook": "storybook build"
}

 

 

스토리북 설치

npx storybook@latest init

노드 버전을 업그레이드 하라며 설치가 중단된 경우에는 [Storybook] 스토리북 설치하기 +) node 버전 업그레이드 에러 해결법 글 참조

 

[Storybook] 스토리북 설치하기 +) node 버전 업그레이드 에러 해결법

Storybook 설치하기 npx storybook@latest init 별 문제가 없다면 중간중간 계속 진행할 건지 물어볼 때마다 y 입력하면 끝난다. 설치는 이것으로 끝이다. 실행하면 localhost:6006로 브라우저를 띄워준다. npm r

bluepebble25.tistory.com

 

 

 

Storybook craco 설정하기

.storybook/main.ts에 있는 내용을 아래에 있는 코드로 대체시켜준다.

const path = require('path')

const toPath = _path => path.join(process.cwd(), _path)

module.exports = {
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/preset-create-react-app',
  ],
  webpackFinal: async config => ({
    ...config,
    resolve: {
      ...config.resolve,
      alias: {
        ...config.resolve.alias,
        '@emotion/core': toPath('node_modules/@emotion/react'),
      },
    },
  }),
}

 

stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],

이 부분은 우리의 .stories 파일이 src/stories/Button.stories 처럼 src/stories라는 경로에 위치하고 있기 때문에 이렇게 작성해 준 것이다. 만약 다른 경로에 스토리 파일을 보관한다면 그에 맞게 경로를 수정해주면 된다.

 

npm run storybook

으로 스토리북을 실행시키면 다음과 같은 에러가 발생할 것이다.

 

npx storybook@next automigrate

를 하면 알아서 부족한 설정들을 보충해준다.

 

최종적인 main.ts 코드

const path = require('path');
const toPath = _path => path.join(process.cwd(), _path);
module.exports = {
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: ['@storybook/addon-links', '@storybook/addon-essentials'],
  webpackFinal: async config => {
    config.module.rules.push({
      test: /\.(ts|tsx)$/,
      loader: require.resolve('babel-loader'),
      options: {
        presets: [['react-app', {
          flow: false,
          typescript: true
        }], require.resolve('@emotion/babel-preset-css-prop')]
      }
    });
    config.resolve.extensions.push('.ts', '.tsx');
    config.resolve.alias = {
      ...config.resolve.alias,
      '@emotion/core': toPath('node_modules/@emotion/react'),
      '@emotion/styled': toPath('node_modules/@emotion/styled'),
      'emotion-theming': toPath('node_modules/@emotion/react')
    };
    return config;
  },
  framework: {
    name: '@storybook/react-webpack5',
    options: {}
  },
  docs: {
    autodocs: true
  }
};

 

실행화면. 완료!

 

+) CRA 경고

dev dependency 중 하나가 없어서 생기는 일. 아래 명령어 실행

npm install --save-dev @babel/plugin-proposal-private-property-in-object

 

One of your dependencies, babel-preset-react-app, is importing the      
"@babel/plugin-proposal-private-property-in-object" package without     
declaring it in its dependencies. This is currently working because     
"@babel/plugin-proposal-private-property-in-object" is already in your  
node_modules folder for unrelated reasons, but it may break at any time.

 

babel-preset-react-app is part of the create-react-app project, which
is not maintianed anymore. It is thus unlikely that this bug will
ever be fixed. Add "@babel/plugin-proposal-private-property-in-object" to
your devDependencies to work around this error. This will make this message
go away.

 

 

 

Reference

https://www.howdy-mj.me/storybook/setting-emotion

 

Storybook에서 Emotion 설정하기

> 해당 글에서 사용된 packages 버전은 아래와 같습니다. package.json ```json { // ...생략 "dependencies": { "@emotion/babel-preset-css-prop": "^11.2.0", "@em...

www.howdy-mj.me

 

'Front-end > 스타일링 라이브러리' 카테고리의 다른 글

[storybook] storybook 컴포넌트 설계 및 문서화하는 법 (+ Emotion, Typescript)  (0) 2023.06.19
[React] emotion 설치 및 typescript에서 사용하기 (pragma 제거방법)  (0) 2022.11.24
    'Front-end/스타일링 라이브러리' 카테고리의 다른 글
    • [storybook] storybook 컴포넌트 설계 및 문서화하는 법 (+ Emotion, Typescript)
    • [React] emotion 설치 및 typescript에서 사용하기 (pragma 제거방법)
    페블_
    페블_

    티스토리툴바