개발

vanilla extract 시작하기

배우겠습니다 2024. 3. 21. 19:21

1. configure

//next.config.js
const {
    createVanillaExtractPlugin
  } = require('@vanilla-extract/next-plugin');
  const withVanillaExtract = createVanillaExtractPlugin();
  
  /** @type {import('next').NextConfig} */
  const nextConfig = {};
  module.exports = withVanillaExtract(nextConfig);

 

공식문서에 있는 것 복붙하면 된다.

require때문에 import문으로 바꾸라는 경고가 거슬릴텐데, 그렇다고 해서 next config를 cjs확장자로 바꾸면 안된다.

 

2. global style

import { globalStyle } from '@vanilla-extract/css';

globalStyle('body', {
  fontFamily: `system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
  Oxygen, Ubuntu, Cantarell, Open Sans, Helvetica Neue, sans-serif`,
});

 

.css.ts형식 파일에 이런거 만들고

import "blabla.css";

 

import 해주자.

그냥 css import하는거랑 똑같다.

 

단 불편한 점이 있다.

globalstyle은 selector사용이 불가능한 것 같다.

globalStyle('a', {
  color: 'inherit',
  textDecoration: 'none',
});

globalStyle('a:hover',{
  textDecoration: 'underline',
})

그래서 이렇게 작성해야한다.

 

//이러면 좋았을 텐데!
globalStyle('a', {
  color: 'blue',
  selectors: { '&:hover': { color: 'red' } },
});

 

다른 방법이 있을 것 같다. globalstyle에 여러 태그를 적용할 수 있지만, 공통된 스타일을 적용하고 싶을 때 사용하는 것 같다.

모든 태그의 기본스타일을 초기화하는 reset css를 사용할 때 그냥 css파일 쓰는게 편할 것 같다.

 

 

3. style

import { style } from "@vanilla-extract/css";

export const navStyle = style({
  backgroundColor: "red",
  padding: "50px 100px",
});

 

import { navStyle } from "./navigation=bar.css";

 <nav className={navStyle}>{child}</nav>

 

css module이랑 사용하는 법이 매우 비슷해보인다.

 

vanilla extract는 빌드타임때 css파일로 바꿔버리는 노런타임 css in js이므로 css랑 사용법이 비슷한 것 같다ㅋㅋ

아직 여러 스타일링 기법중 뭐가 제일 좋다하기엔 이른 것 같다. 더 개발해봐야겠다.

하지만 css in js를 nextjs에서 사용하고 싶을 때 서버 컴포넌트에선 불가능하다는 단점이 있었지만,

빌드타임 css in js가 그 대안이 될 수 있었고,

다른 라이브러리인 styleX는 정보가 너무 부족해서 vanilla extract를 선택했다.