LoginSignup
5
2

Tailwind CSSのpurgeを開発環境でも適用する

Last updated at Posted at 2021-06-29

起きたこと

  • Next.js のプロジェクトに Tailwind CSS をインストールした
  • 開発環境で Tailwind CSS が適用されていることを確認したので、試しにvercel にデプロイしてみた
  • 下の画像のように、見え方に差異が生じていた
開発環境 本番環境
スクリーンショット 2021-06-30 0.54.21.png スクリーンショット 2021-06-30 0.54.08.png

何が起きていたか

tailwind.config.js に記載していた、purge の設定が良くない様子。
purge は未使用の Tailwind CSS のスタイルを build 時に削除してくれるものです。

tailwind.config.js
module.exports = {
  purge: {
    './components/**/*.jsx',
    './pages/**/*.jsx'
  },
  darkMode: false,
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

ドキュメントを読んでみたところ、下記のように記載されていた。

Now whenever you compile your CSS with NODE_ENV set to production, Tailwind will automatically purge unused styles from your CSS.

要はプロダクション環境時に、purge されるよ、とのこと、なるほど。

試しに開発環境で、build して、本番環境のように、Next.js を実行してみる。

yarn run next build
yarn run next start

下記のような画面が立ち上がりました、Vercel にデプロイした画面と同じですね。

開発環境でNext.jsをプロダクションビルドして起動した画面

解決

再びドキュメントを読む

If you want to manually control whether unused styles should be removed (instead of depending implicitly on the environment variable), you can use an object syntax and provide the enabled option, specifying your templates using the content option:

enabled というオプションを利用することで、解決できそうです。

tailwind.config.js
module.exports = {
  purge: {
    enabled: true,
    content: ['./components/**/*.jsx', './pages/**/*.jsx']
  },
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

開発環境で立ち上げて確認してみましょう。

yarn run next dev

開発環境の画面

本番に合わせることができました。
ファイルを変更してホットリロード時のコンパイルが若干遅くなってしまっているようにも感じましたが、開発で見ていたものと、本番に上げた時に見え方が違うのは少々困るので仕方無しなのかな。。。

また調べてみます。

5
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2