cssnano: minifying CSS
Minification means shrinking CSS without changing its meaning: whitespace, line breaks and comments are removed, values are written shorter. The file downloads faster, and the browser applies it exactly the same. In PostCSS the cssnano plugin does this.
Installing
npm install --save-dev cssnanocssnano goes last — you minify the finished CSS:
// postcss.config.js
import postcssImport from 'postcss-import';
import postcssPresetEnv from 'postcss-preset-env';
import cssnano from 'cssnano';
export default {
plugins: [postcssImport(), postcssPresetEnv(), cssnano()],
};What it does
Take post card styles with the excesses typical of hand-written code:
/* styles/main.css */
/* Post card */
.post-card {
margin: 0px 0px 16px 0px;
padding: 16px;
color: #ffffff;
background-color: #2563eb;
font-weight: normal;
}
.post-card {
border-radius: 8px;
}
.post-title {
font-weight: bold;
transition: color 0.30s ease;
}To see cssnano alone at work, temporarily keep only it in plugins and run npx postcss styles/main.css -o css/main.css:
.post-card{margin:0 0 16px;padding:16px;color:#fff;background-color:#2563eb;font-weight:400;border-radius:8px}.post-title{font-weight:700;transition:color .3s}All the CSS fits on one line, and the file became about one and a half times smaller (254 bytes before, 159 after). The changes in order:
| Before | After | Why |
|---|---|---|
| Comment and whitespace | — | The browser does not need them |
0px 0px 16px 0px | 0 0 16px | Zero without a unit, repeated side removed |
#ffffff | #fff | Short color notation |
normal, bold | 400, 700 | Numbers are shorter than words |
0.30s ease | .3s | ease is the default |
Two .post-card rules | One | Declarations merged |
Comments you need to keep
cssnano keeps a comment that starts with /*! — that is how licenses are usually preserved:
/* styles/main.css */
/*! Blog styles v1.0 */
.post-tag {
color: red;
}/*! Blog styles v1.0 */.post-tag{color:red}When to minify
Minified CSS is hard to read in developer tools, so cssnano is enabled only for the build that goes to the server, while during work you keep normal output. The production build lesson shows how to switch this with one command. A Vite project does not need cssnano: npm run build minifies CSS by itself.
Common mistake
Putting cssnano anywhere but last. Plugins after it receive minified CSS, and whatever they add — prefixes, unwrapped nesting — stays unminified. Keep cssnano at the end of the plugins array.