00

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.

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

Code Examples

enable optimization configuration in webpack with uglify

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()],
  },
};
Brian Love

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Discussions are healthy ❤️