본문 바로가기
프로젝트

역시 모든 고난의 시작은 환경설정 세팅이다.

by 반갑조? 2024. 11. 11.

부제: emotion의 css prop을 사용하기 위한 craco설치

 

늘 하던것처럼 create-react-app(이하 cra)로 react프로젝트를 만들었다.

css라이브러리로 mui와 emotion을 사용할 예정이다(세부 조정은 emotion css prop을 사용).

mui와 emotion설치까지는 순조로웠다.

emotion의 css prop이 작동을 하는지 확인하기 위해  'Hello Emotion!' 이라는 문구의 폰트컬러를 red로 설정했지만 적용되지 않아서 알아보기 시작했다.

(해결한 방법은 하단에 있습니다.)

 

1. @jsxImportSource 주석

코드 최상단에 아래 주석을 입력한다.

/** @jsxImportSource @emotion/react */

이 주석은 babel이 jsx를 변환할 때 React.createElement 대신 emotion의 jsx 함수를 사용하게 해준다.

하지만 이 주석을 코드 파일마다 상단에 적어야해서 비효율적이다.

 

2. Babel plugin 설정

@emotion/babel-plugin 을 개발의존성(devDependencies)으로 설치

npm install @emotion/babel-plugin --save-dev

위 설치 후 babel설정 파일(.babelrc)에 플러그인 추가

'.babelrc`파일에 아래를 설정.

{
  "plugins": ["@emotion/babel-plugin"]
}

하지만 여전히 작동되지 않는다. 위의 주석이 있어야만 글자가 red로 변한다,,,,

 

그러다 발견한 경고메시지

' 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" toyour devDependencies to work around this error. This will make this message go away.'

위 문구는 babel-preset-react-app이 @babel/plugin-proposal-private-property-in-object 패키지를 종속성에 명시하지 않아서 발생하는 경고이다. 현재는 node_modules에 이 패키지가 이미 존재해서 문제가 발생하지 않지만, 언젠가는 이 패키지가 누락되면 에러가 발생할 수 있다고 알려주고 있다.

그래서 이 문구대로 한다면

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

 

마찬가지로 devDependencies에 설치하면 된다. 그러면 경고메시지가 사라진다.

그러나 css적용은 여전히 되지 않는다...!

 

cra에서 eject명령을 실행해도 된다고하지만 eject를 하면 cra의 자동 업데이트  해택을 받으 수 없고 eject는 영구적이여서 설정 변경이 필요한 경우에만 사용하는것이 좋다고 한다.

 

3. (이제부터 해결한 방법!!) Craco

그래서 `craco`를 사용할것이다.

cra를 사용하는 프로젝트에서는 babel설정을 직접 수정할 수 없는 제한이 있기 때문에 위의 방법을 수행해도 안되는 경우에는 Craco(Create React App Configuration Override)를 활용해서 필요한 설정을 적용할 수 있다.

craco는 cra의 기본 설정을 유지하면서 일부 설정을 오버라이드할 수 있도록 도와주는 도구이다.

 

- 설치

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

@emotion/babel-preset-css-prop은 emotion 설정을 더 간편하게 관리하도록 도와주는 프리셋이라고 하지만 설치해보았다.

 

- package.json 수정

script섹션의 react-script를 craco로 바꾸어야한다.

"scripts": {
  "start": "craco start",
  "build": "craco build",
  "test": "craco test",
  "eject": "react-scripts eject"
}

그러면 craco가 react-script 대신 설정 파일을 읽어들여 프로젝트 빌드를 관리하게 된다.

 

- craco설정 파일 생성

프로젝트 루트에 `craco.config.js` 파일을 생성하고 Babel 플러그인을 추가한다.

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

여기까지하면 emotion 플러그인이 적용되어서 css prop을 사용할 때 매번 @jsxImportSource주석을 상단에 추가할 필요가 없어진다!

 

그러면

import { css } from '@emotion/react';
import React from 'react';

const MyComponent = () => (
  <div css={css`color: red;`}>
    Hello, Emotion!
  </div>
);

export default MyComponent;

위 코드를 실행하면 'Hello, Emotion!' 문구의 색상이 red가 된것을 볼 수 있다!!

 

드디어 적용이 되었다!! 얏호!