New Best Practice
Sign In

Minify and Eliminate Dead JavaScript Code

Wednesday, February 19, 2020

While web applications and single page applications are increasingly client-driven, the result is an increase in the payload size of JavaScript that is necessary for the application to function. Further, more users are consuming web applications via mobile devices and a cellular connection than ever before. Both of these forces are resulting in the need to minify and eliminate dead (or unused) JavaScript code.

There are several open-source tools available to JavaScript developers to minify and eliminate dead code:

  1. Uglify
  2. Closure Compiler

Uglify can also be used with webpack in order to both bundle your JavaScript application as well as to minify and remove unused code as a plugin to webpack.

Code Examples

const path = require('path');
const uglify = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ]
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  optimization: {
    minimizer: [new uglify()],
  },
};

do: enable optimization configuration in webpack with uglify

Instructions

  • Do:

    minify and eliminate dead code

  • Consider:

    using the webpack uglify plugin to bundle, minimize, and eliminate dead (unused) code

  • Why:

    minimize network request bandwidth, especially for cellular connected devices

Brian Love

Brian is a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. He regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, Brian enjoys skiing, hiking, and being in the outdoors. Brian recently launched lookout.dev where you can find best practices and expert advice on topics ranging from TypeScript, Angular, React, Node.js and more.

Google Developers Expert

Discussions are healthy ❤️