How to Minify CSS and JavaScript
· Category: Web Performance
Short answer
Minification removes unnecessary characters from code without changing functionality. It reduces file sizes and improves download times.
Steps
- Use Terser or UglifyJS for JavaScript minification.
- Use cssnano or CleanCSS for CSS minification.
- Integrate minifiers into your build pipeline with Webpack, Vite, or Rollup.
- Enable source maps to map minified code back to the original for debugging.
- Verify that the minified output still passes your test suite.
Tips
- Combine minification with Gzip or Brotli compression for maximum savings.
- Remove console logs and debug code before minifying production builds.
- Use mangling cautiously if your code relies on specific function names.
Common issues
- Aggressive minification can break code that uses
evalor stringified functions. - Missing semicolons may cause parsing errors in minified output.