かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

Vite PostCSS で CSS をネストして書けるようにしたい

PostCSS はデフォルトでは Sass のようなネストでスタイルを書くことができません。
Global 用のスタイルを書くときなどにネストできないとちょっと不便なので PostCSS を使ってネストして CSS を書けるようにしたメモ

Vite (react) のプロジェクトに PostCSS-nesting を導入する

$ npm i -D postcss-nesting

PostCSS-nested v.s. PostCSS-nesting

PostCSS Nesting lets you nest style rules inside each other, following the CSS Nesting specification. If you want nested rules the same way Sass works you might want to use PostCSS Nested instead.

SCSS っぽく書きたいなら postcss-nested を選択すれば良さそう

vite.config.jscss のセクションを追加して postcss-nesting の設定を追加すれば OK

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
import postcssNesting from "postcss-nesting";

export default defineConfig({
  plugins: [react(), tsconfigPaths(), svgr()],
  css: {
    postcss: {
      plugins: [postcssNesting],
    },
  },
  server: { port: 3000 },
});

📝 PostCSS はセレクタをネストさせる時に & が必要

🙅 Scss と同じ書き方をしても意図したとおりにコンパイルされない

.foo {
  h1 { color: red; }
}

🙆 PostCSS-nesting ではネストさせるセレクタの前に & が必要

.foo {
  & h1 { color: red; }
}

PostCSS を使ってネストした CSS が書けるようになりました。ただネストは詳細度が上がりメンテナンス性を損なう場合があるので使いすぎには注意しましょう!

おわり ₍ ᐢ. ̫ .ᐢ ₎


[参考]

最近作業中にずっとヨルシカ聴いてる