LinariaというCSS in JSのライブラリを知ったので調査した
Linaria はゼロランタイム CSS in JS ライブラリ
前回、同じゼロランタイム CSS in JSライブラリのVanilla Extract を調べたがそれとほぼ同様のメリットがある
【Vanilla Extract】Vanilla Extract とは - UGA Boxxx
構築できる環境は以下
- webpack
- esbuild
- Rollup
- Svelte
Viteの設定はREADMEに書かれていなかったが、Exampleにはあり、Rollupの環境設定方法を見ながら構築することになりそう
https://github.com/callstack/linaria/tree/master/examples/vite
Next.jsは公式にはプラグインが出ておらず、今は以下を利用して動かすことができる見たい
Babelは必須でプラグインインストールと設定が必要
$ npm install @linaria/core @linaria/react @linaria/babel-preset
{ "presets": [ "@babel/preset-env", "@babel/preset-react", "@linaria" ] }
構文は以下のような感じで、Styled-Componentsと同様にバッククオート「`」の中にCSS構文で書く
import { css } from '@linaria/core'; import { modularScale, hiDPI } from 'polished'; import fonts from './fonts'; // Write your styles in `css` tag const header = css` text-transform: uppercase; font-family: ${fonts.heading}; font-size: ${modularScale(2)}; ${hiDPI(1.5)} { font-size: ${modularScale(2.5)}; } `; // Then use it as a class name <h1 className={header}>Hello world</h1>;
ただ、上記のcss
を使う場合はpropが使えないので、Styled-Componentsのような動的なスタイルを当てられない
動的にやりたい場合のやり方はドキュメント内でいくつか紹介されている
https://github.com/callstack/linaria/blob/master/docs/DYNAMIC_STYLES.md
もし、Reactコンポーネントで利用する場合はcss
の代わりにstyled
を利用することが可能で、これであればpropが渡せるみたいなのでReactならstyled
を使う方がよさそう
設定がやや面倒そうではあるが、Styled-Componentsと同じ書き心地でゼロランタイムなのがLinariaの魅力かなと感じた