TailwindCSS dark mode can't change <html> or add class="dark" tag on production build

Updated: Feb 09, 2025

TailwindCSS dark mode can't change <html> or add class="dark" tag on production build

I've been trying to implement TailwindCSS dark mode in my React app. I've followed the official documentation and it works fine in development mode. However, when I build the app for production, the dark mode doesn't work. I've tried adding the class="dark" tag to the html tag in the index.html file, but it doesn't seem to make a difference.

Here's what I've done so far:

  1. Installed TailwindCSS and PostCSS: npm install tailwindcss postcss autoprefixer
  2. Created a postcss.config.js file:
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
  1. Added the following lines to the tailwind.config.js file:
module.exports = {
  purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};
  1. Added the following lines to the index.html file:
<html lang="en" class="dark:bg-gray-900">
  <head>
    <!-- ... -->
  </head>
  <body>
    <!-- ... -->
  </body>
</html>
  1. Added the following lines to the webpack.config.js file:
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  // ...
  optimization: {
    minimizer: [
      new TerserPlugin(),
      new CssMinimizerPlugin(),
    ],
  },
};
  1. Added the following lines to the package.json file:
"scripts": {
  "start": "webpack serve --mode development --open",
  "build": "webpack --mode production"
}
  1. Added the following lines to the webpack.dev.config.js file:
module.exports = {
  // ...
  devServer: {
    contentBase: './dist',
  },
};

Despite all these efforts, the dark mode still doesn't work in production. I've also tried setting the darkMode option to 'media' and 'class' in the tailwind.config.js file, but it didn't make a difference either.

Any help would be greatly appreciated!