I’m trying to setup a Next.js project with CSS modules and I’d like to use PurgeCSS to clean up unused css classes. I setup the plugin in a postcss.config.mjs file, but while “normal” css is purged as intended CSS modules are not.
PurgeCSS website has an old example on how to set up for CSS modules with CRA and Webpack. I’m not really proficient in Webpack but it looks like the idea is to make sure that the CSS modules hashes are computed before PostCSS runs.
If that’s the case I think it should be possibile to do it with Next too, but I’m not sure what the next.config.mjs
file should look like. The example below fails at purging unused classes both in “normal” CSS files and in hashed CSS modules, so I think either PostCSS or the PurgeCSS plugin aren’t running at all.
import cssLoader from "css-loader"
import postcssLoader from "postcss-loader"
import postcssPurgecss from "@fullhuman/postcss-purgecss"
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (
config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
) => {
const getStyleLoaders = (cssOptions) => {
return [
{
loader: cssLoader,
options: cssOptions
},
{
loader: postcssLoader,
options: {
plugins: () => [
postcssPurgecss({
content: ['**/*.{jsx,tsx}'],
defaultExtractor: content => content.match(/[w-/:]+(?<!:)/g) || [],
safelist: ["html", "body"]
}),
],
}
}
];
};
Object.assign(
config.module.rules,
{
oneOf: [
{
test: /.module.css$/,
use: getStyleLoaders({
importLoaders: 2,
modules: true,
})
}
]
}
)
return config
}
};
export default nextConfig;
How can I setup PostCSS from in the next config file so that both “normal” and module CSS files are purged of unused classes?