개발 공부 일지/Library
[vanilla extract] .css.ts 안에서 코드 작성하기
yelimu
2025. 2. 26. 18:07
vanilla extract 를 사용해보려고 한다.
- 빌드타임때 css파일로 바꿔버리는 Zero-runtime CSS in JS → Runtime CSS in JS 성능상 문제를 해결
- vanilla-extract로 쓴 코드는 자바스크립트 번들 사이즈에 영향을 주지 않는다. 즉, 브라우저에서 번들 결과를 남기는 것이 아닌 편집하는 동안 코드를 실행
- vanilla-extract에서는 createVar를 사용하여 컴포넌트 또는 스타일 범위 내에서 CSS 변수를 사용 (로컬 스코프)
- class name : 컴파일 후에는 고유한 이름(예: button_abc123)이 생성되어 사용됩니다. (로컬 스코프)
- 설치 & 설정
pnpm install @vanilla-extract/css @vanilla-extract/next-plugin
// next.config.js
const {
createVanillaExtractPlugin
} = require('@vanilla-extract/next-plugin');
const withVanillaExtract = createVanillaExtractPlugin();
/** @type {import('next').NextConfig} */
const nextConfig = {};
module.exports = withVanillaExtract(nextConfig);
//tsconfig.json
{
"compilerOptions": {
"types": ["@vanilla-extract/css"],
}
}
공식 홈페이지에 나와있는 예제 따라해보기
// page.tsx
import { container } from "./style.css";
const Home = () => {
return (
<>
<h1 className={container}>helloworld </h1>
</>
);
};
export default Home;
// style.css.ts
import { style } from "@vanilla-extract/css";
export const container = style({
padding: 10, // px 단위 생략
});
Styled Component 와 비슷할 거라고 생각했는데, CSS in JS 라며 왜 스타일 시트를 따로 만드는거지?! 싶어서 ...
//page.tsx
import { style } from "@vanilla-extract/css";
const container = style({
padding: 10, // px 단위 생략
});
const Home = () => {
return (
<>
<h1 className={container}>helloworld </h1>
</>
);
};
export default Home;
스타일 코드를 page.tsx로 가지고왔더니 이런 에러가 발생했다.
Error: Styles were unable to be assigned to a file. This is generally caused by one of the following: - You may have created styles outside of a '.css.ts' context - You may have incorrect configuration. See https://vanilla-extract.style/documentation/getting-started
vanilla-extract에서는 스타일 정의가 반드시 .css.ts 파일 내에서 이루어져야 한다고 한다.
CSS-in-JS는 기본적으로 스타일을 JavaScript 파일 내에서 정의하고, 그 스타일을 JavaScript로 처리하는 방식
vanilla-extract는 스타일을 TypeScript 파일 내에서 정의하고, 빌드타입에 ts 파일을 CSS 파일로 컴파일하는 방식
그러니까 home.tsx 가 아니라 style.css.ts <- TypeScript 파일 내에서 정의!