설치
명령어로 다음과 같은 패키지를 설치해줍니다.
$ yarn add @emotion/styled @emotion/react
TypeScript 환경에서 사용하기 위해서는 tsconfig.json에 jsxImportSource를 추가해 주어야 합니다.
// tsconfig.json
{
"compilerOptions": {
//...
"jsxImportSource": "@emotion/react"
}
}
Global Styles
우선 Globalstyle.tsx 파일을 생성하고 아래와 같이 작성해줍니다.
// GlobalStyle.tsx
import { css, Global } from '@emotion/react';
const style = css`
/* global로 사용할 css 작성 */
`
const GlobalStyle = () => {
return <Global styles={style} />
}
export default GlobalStyle;
그 후, _app.tsx 파일에 해당 컴포넌트를 추가해주면 됩니다.
// _app.tsx
import GlobalStyle from "./styles/GlobalStyle";
function App() {
return (
<>
<GlobalStyle />
{/* ... */}
</>
);
}
export default App;
Font
index.html 파일 내에 폰트를 추가해줍니다.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<!-- 폰트 추가 -->
<link rel="stylesheet" as="style" crossorigin href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.8/dist/web/variable/pretendardvariable-dynamic-subset.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
그 후, 생성해둔 GlobalStyle.tsx에 폰트를 적용해주면 됩니다.
// GlobalStyle.tsx
import { css, Global } from '@emotion/react';
const style = css`
/* 폰트 적용 */
body {
font-family: "Pretendard Variable", Pretendard, -apple-system, BlinkMacSystemFont, system-ui, Roboto, "Helvetica Neue", "Segoe UI", "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif;
}
`
const GlobalStyle = () => {
return <Global styles={style} />
}
export default GlobalStyle;
Variables
변수를 관리할 파일을 생성합니다.
// Variables.ts
export const Variables = {
colors: {
primary: "#fe4902",
},
};
그 후, 변수를 사용할 컴포넌트에 import 하고 사용할 수 있습니다.
import { Variables } from "styles/Variables";
...
const Container = styled.div`
background-color: ${Variables.colors.primary};
`;
Theming
작업하면서 작성중...
https://www.howdy-mj.me/css/emotionjs-intro
emotion.js 소개 및 사용법 (feat. CSS-in-JS)
업데이트: 2021.05.12 - 주요 내용: @emotion/core 10.0.28 => @emotion/react 11.4.0 업데이트: 2021.05.19 - 주요 내용: Global에서 사용하기, type 설정 ## emotion.js란? emo...
www.howdy-mj.me
https://leo-xee.github.io/CSS/emoion-basic/
Emotion
이 글에서는 Next.js와 Typescript 환경에 Emotion을 적용하고 GlobalStyle, Theming 그리고 폰트 적용과 같은 주요 기능의 사용법을 정리합니다. Emotion Emotion은 개발자 친화적인 CSS-in-JS 라이브러리이다. 일반
leo-xee.github.io
'React' 카테고리의 다른 글
[React] Tailwind (0) | 2023.12.18 |
---|---|
[React] Next.js 13 (0) | 2023.08.09 |
[React] Vite 절대 경로 설정 (0) | 2023.07.06 |
[React] Create React App 이미지 경로 (0) | 2023.05.23 |