언어/React

@emotion/react 윈도우 설치

김뱅쓰 2023. 3. 1. 15:43

@emotion/react 설치

npm install --save @emotion/react

  

 

@styled emotion 설치 (styled를 사용하여 css적용) (나는 개인적으로 이것까지만 사용)

npm add @emotion/styled

 

@emotion/babel-plugin 설치 (컴포넌트에 바로 css를 적을 수 있게하는 ) (생각보다 설치 복잡) (이건 안해도 됨)(아니 그냥하지마)

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

babel을 적용하기위해서는 .babelrc 파일을 만들어서 plugin에 특정 값을 넣어주어야 하는데 create-react에서는

babelrc가 적용되지 않는다.

그래서 대체로 프레그마를 이용한다. 

원래 /** @jsx jsx*/ 이런 프레그마가 들어가는데 babelrc 파일이 없어서 적용이 안된다.

/** @jsx jsx*/  대신 /** @jsxImportSource @emotion/react */를 코드맨위 적어준다.

 

프레그마는: 컴파일러에게 이 파일을 어떻게 처리할지 알리는 것

 

매번 프레그마를 넣어주기는 귀찮기 때문에 대신할 2가지 방법이 있다.

1. eject라는 명령을 쓴다. - 코드가 지저분해진다.

2. croco 라이브러리 사용 - 설정을 오버라이드해서 적용해준다.

 

2. croco 라이브러리 사용

arn add -D @craco/craco 을 터미널에 입력하고 (imac)

(window)

npm i -D @craco/craco

craco.config.js 파일 생성

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

그 파일에 위 코드 작성하고 @emotion/babel-preset-css-prop을 설치해줘야 한다.

arn add -D @emotion/babel-preset-css-prop (imac)

(window)

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

그리고 package.json파일에 script부분의 start,build,test 의

react-scripts start   ->   craco start

이렇게 바꿔준다.

 

craco ( create-react-app-config-override )


 

 

@emotion libary를 쓰는 이유

따로 js 파일을 만들지 않고도 빌드하면 자동으로 class 명과 stylesheet를 만들어준다. (따로 css파일을 만들지 않아도 됨)

 

그냥 스타일링과 styled 의 코드 비교

그냥 스타일링

const Box = ({width=100,height=100,backgroundColor="red"}) => {
    const style = {
        width,
        height,
        backgroundColor,
    };
    return <div style={style}/>;

};

export default Box;

styled

import styled from "@emotion/styled";

const Box = styled.div`
    width: 100px;
    height: 100px;
    background-color: cyan;
    `;

    export default Box;

+babel (이건 app.js 에 만듬)

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

const style = css`
  color: hotpink;
`;

const Box1 = ({children}) => (
  <div css={style}>
    test
    {children}
  </div>
)