티스토리 뷰

React

emotion 사용시 jsx pragma 제거하기

심재철 2020. 4. 17. 16:10

https://medium.com/@harryhedger/quick-how-to-use-the-emotion-css-prop-with-create-react-app-5f6aa0f0c5c5

 

Quick How-to: Use the emotion `css` prop with create-react-app

I’ve heard a few people have had trouble getting emotion’scss prop to work with create-react-app, so here’s how to do it:

medium.com

이모션을 사용할때 @emotion/core의 css prop을 활성화 시키려고 할때

 

/** @jsx */
import {jsx, css} from '@emotion/core';

...

와 같은 쓸데없는 코드를 계속해서 입력해줘야하는 불편함이 있다. 이 보일러 플레이트 코드를 제거하기 위해서는 바벨 설정을 해주면 된다.

 

하지만 문제는, CRA에서는 기본적으로 바벨 설정을 커스텀을 막아놓았다. react-app-rewired를 활용해야 바벨 설정을 변경시킬 수 있다.

스텝

npm에서 @emotion/babel-preset-css-prop을 우선 설치해준다. 이 프리셋 덕분에 바벨이 이모션의 css를 이해할 수 있게 되었고 /** @jsx */와 같은 jsx pragma를 선언해주지 않아도 이모션의 jsx함수를 호출해서 컴포넌트를 렌더링한다.(리액트의 React.createElement가 아니라) 또한 컴파일된 파일 최상단에 jsx를 자동으로 import해주기 때문에 우리가 코드에 직접 import하지 않아도 되는것이다.

 

 

Create config-overrides.js in your project root

const { override, addBabelPreset } = require('customize-cra')
module.exports = override(
  addBabelPreset('@emotion/babel-preset-css-prop')
)

이렇게 해주면 이제 emotion의 css를 사용할 수 있게 된다.

import React from 'react'
import { css } from '@emotion/core'
const Example = () => <div css={css`width: 100%`}>Example</div>

 

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함