Vite 환경에서 emotion의 pragma 반복을 줄여보기
목차
· 포스팅 동기
· vite.config.js 설정해주기
· tsconfig.json 설정해주기
· [부록] 타입스크립트를 사용하는데, DetailedHTMLProps 에러가 발생한다면?
포스팅 동기
최근 프로젝트에서는 tailwind를 접했지만, 다시 다양한 프로젝트를 접하면서 emotion을 사용할 일의 빈도가 많아졌다.
요즘에는 Vite 환경에 매료되어, 다양하게 배워보고자 Vite 환경과 pnpm을 접목한 프로젝트를 진행을 하였고, 프로젝트 안에서 각 컴포넌트마다 pragma를 기재해주는 것이 매번 불편한 상황 중 하나였다.
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";
/** @jsxImportSource @emotion/react */ 와 같은 이 부분을 JSX pragma라고 한다. babel 트랜스파일러에게 JSX 코드를 변환할 때, React의 jsx() 함수가 아니라 Emotion의 jsx() 함수를 대신 사용하라고 알려주기 위함이다. 이를 작성하지 않으면 css prop에 적용된 스타일이 제대로 반영되지 않는다.
이를 해결하기 위해 babel 설정을 통해 굳이 pragma를 컴포넌트 별로 기재하지 않아도 css props 하나만을 통해 쉽게 접근하고자 했다. vite를 제외한 다른 빌드 매니저의 경우, babel 설정을 따로 진행을 해줘야하지만 vite의 경우 plugin과 몇 개의 설정을 통해 손쉽게 pragma 사용의 반복을 줄여 프로젝트에 emotion 도입을 원활하게 할 수 있다.
vite.config.js 설정해주기
/* vite.config.ts */
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react({
jsxImportSource: '@emotion/react',
babel: {
plugins: ['@emotion/babel-plugin'],
},
}),
],
});
tsconfig.json 설정해주기
/* tsconfig.json */
{
"compilerOptions": {
// ...
"jsxImportSource": "@emotion/react"
}
}
[부록] 타입스크립트를 사용하는데, DetailedHTMLProps 에러가 발생한다면?
TypeScript에서 DetailedHTMLProps에 HTMLElement에 {childrent : ReactNodes; css : SerializedSyleds;} 를 할당하려고 했을 때, 실패하며 특히 css 속성을 추가하려고 시도했지만 HTMLElement에는 이에 맞는 css 속성이 존재하지 않기 때문에 실패했다는 에러이다. 그렇기 때문에 DetaildHTMLProps에 이에 걸맞는 타입을 추가해줘야한다.
DetailedHTMLProps는 React의 HTML 속성과 이벤트를 모두 포함하는 인터페이스이다. 요소를 나타내는 HTML 태그의 인터페이스이며, css 속성은 기본적으로 HTML 속성에 포함되어있지 않기 때문에 오류가 발생한다. 이 문제를 해결하려면 HTMLElement 대신에 React.HTMLProps 또는 React.HTMLAttributes를 사용하여 DetailedHTMLProps 인터페이스에 css 속성을 추가해야한다. 이렇게 함으로서 DetaildHTMLProps를 통해서 제공하는 react 기본 기능을 모두 제공하면서도, emotion의 css-props를 추가하기 위해 기능을 추가하기 위해 기능을 추가해주어야한다.
tsconfig.json의 complierOptions 중 types를 @emotion/react/types/css-props를 사용하며, react 기본 제공 타입 + css 타입을 사용할 수 있게 된 것이다. complierOptions의 types는 선언된 모듈만을 포함하기 때문에 React 기본 DetailedHTMLProps에 추가되지 않지만, @emotion/react 라이브러리의 경우 interface Attributes + css 가 포함되었기 때문에 가능한 것이다. 그래서 위의 에러가 발생했을 때 아래와 같이 해결이 가능하다.
/* tsconfig.json */
{
"compilerOptions": {
// ...
"types": ["@emotion/react/types/css-prop"]
}
}
레퍼런스
Emotion – The css Prop
The primary way to style elements with emotion is the css prop. It provides a concise and flexible API to style your components. There are 2 ways to get started with the css prop. Both methods result in the same compiled code. After adding the preset or se
emotion.sh
[React] Emotion CSS(인라인) 사용하려면 주석을 이용(CRA)
error message You are loading @emotion/react when it is already loaded. Running multiple instances may cause problems. This can happen if multiple versions are used, or if multiple builds of the same version are used. You have tried to stringify object ret
zindex.tistory.com
[React] Emotion 설치 후 간단한 예제 만들어보기
Emotion은 JavaScript로 css 스타일을 작성하도록 설계된 라이브러리입니다.
velog.io
Emotion 사용 중 발생한 DetailedHTMLProps 이슈 해결하기
구글링은 좀 해봤어, 다른 사람은 어떻게 문제를 해결할까? emotion/react 의 css function을 사용하면서 이게 왜 되는거지? 라고 의심해본 사람
velog.io