Emotion 사용해보기

고석진
4 min readMar 17, 2021

--

# Storybook

스토리북 프로젝트를 세팅한다.

$ npx sb init

# 설치

$ npm i -D react react-dom
$ npm i -S @emotion/core @emotion/styled @emotion/react

# Babel

$ npm i -D @babel/preset-typescript @babel/preset-env @babel/core @emotion/babel-preset-css-prop 

.babelrc

react-preset 대신 emotion-babel-preset 을 이용한다. 이 설정을 통하여 모든 파일마다 들어가는 emotion 주석 생략이 가능하다.

# Typescript

$ npm i -S typescript
$ npm i -D tsconfig-paths-webpack-plugin

tsconfig.json

types 에 emotion 관련 type 설정 추가가 필요합니다.

.storybook/main.js

typescript, emotion 관련 설정을 추가한다.
css`` 문법을 사용하려면 emotion 관련 babel 설정을 추가로 해주어야한다.

추가적으로 @storybook/addon-docs 의 emotion 10 을 사용하고있는데 최신 emotion 과 충돌이 일어난다 (하위호환 … ㅂㄷㅂㄷ)
이를 해결하기위해 alias 를 추가하여 우회하도록한다.

# 컴포넌트 추가

@emotion/styled 를 이용하면 특정 style 을 가진 컴포넌트 생성이 가능하다. styled-components 와 비슷하게 사용한다.

# Storybook 실행

$ npm run storybook

# Emotion 을 이용한 스타일 선업법

  1. @emotion/styled
import styled from "@emotion/styled";const Text = styled.<원하는태그 ex.h1/h2/div 등>``

동적으로 스타일에 변경이 필요하다면 emotion/styled 를 사용하여 컴포넌트를 생성후 props 를 이용하여 동적으로 스타일 변경이 가능하다.

2. @emotion/react 의 CSS 함수를 이용한 스타일 선언

css 를 이용하면 인라인 또는 변수로 분리하여 선언이 가능하다.

3. Mixins 을 이용한 스타일 혼합

@emotion/react 의 CSS 을 기본적으로 mixin 을 제공한다.
이를 활용하여 다양한 스타일을 조합하여 사용이 가능하다.

4. 동적으로 스타일 변경하기

styled 를 이용하여 만들어진 결과물은 리액트 컴포넌트이기 때문에 외부에서 props 를 전달받는 것이 가능하다. 이를 이용하면 동적으로 스타일 조절이 가능해진다.

styled 를 이용하여 만들어진 Text 컴포넌트는 외부로부터 text type, line-height, color 를 받아 동적으로 스타일링을 한다.

# 배포

gh-pages 를 이용하여 배포합니다.

$ npm run build-storybook
$ npx gh-pages -d storybook-static
아래주소로 배포됩니다.
https://<github name>.github.io/<repo-name>/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

고석진
고석진

Written by 고석진

자바스크립트를 사랑하는 프론트 개발자 입니다 :)

No responses yet

Write a response