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

  1. Use Terser or UglifyJS for JavaScript minification.
  2. Use cssnano or CleanCSS for CSS minification.
  3. Integrate minifiers into your build pipeline with Webpack, Vite, or Rollup.
  4. Enable source maps to map minified code back to the original for debugging.
  5. 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 eval or stringified functions.
  • Missing semicolons may cause parsing errors in minified output.