This is a list of all the things I know, and all the things we’ve used to reduce the bundle size of the Peacock / SkyShowtime / NOW TV app. You’re more than welcome to use this checklist to improve your own projects.

  • Create target-specific builds (specially relevant when the same codebase is used for PlayStation, Xbox, Nvidia Shield, Fire TV, etc). In a browser context this would mean creating at least two different builds: one for older browsers that you support (IE, Opera Mini, etc) and another for more modern browsers.

  • Implement code-splitting (by using dynamic imports).

  • Load page-specific code only when the user visits that page.

  • Load feature-specific code only when the user uses that feature. Example: in a chat app with an emoji-picker, only load the emoji-picker when the user clicks a button.

  • Remove duplicate dependencies.

  • Rewrite dependencies.

  • Eliminate dependencies. Example: delete unused polyfills for browsers that you no longer support.

  • Use a minifier / bundler (like Terser, SWC, Oxc, esbuild, etc). It’s incredible how much these tools can squeeze our code. They delete comments, inline single-use functions, collapse multiple variable declarations into a single one, etc.

  • Go over all the options of the minifier you’re using. Go beyond the tool’s defaults. Read its documentation. Example: Terser only does one pass by default. If you use passes: 2 minification takes longer but results are better.

  • In the minifier settings specify the ECMAScript version appropriate for your target. You should know what browsers implement what ECMAScript versions. You should also know what language features are implemented in what ECMAScript versions. There’s a big difference between transpiling to ES5 and ES2021. Example:

    // ES5
    var q = 'my query';
    var searchParams = { q: q };
    
    // ES6
    var q = 'my query';
    var searchParams = { q };
    
  • Use language features that lead to smaller code. Example:

    if (!eventListeners[eventName]) {
      eventListeners[eventName] = [];
    }
    eventListeners[eventName].push(listener);
    

    can be rewritten using the logical OR assignment operator:

    (eventListeners[eventName] ||= []).push(listener);
    
  • However, be aware of what your most important target (browser) is. Example:

    possiblyUndefinedObject && possiblyUndefinedObject.prop
    

    can be rewritten using the optional chaining operator:

    possiblyUndefinedObject?.prop
    

    but using optional chaining on a browser that does not support it leads to a larger bundle due to code transpilation:

    possiblyUndefinedObject === null || possiblyUndefinedObject === void 0 ? void 0 : possiblyUndefinedObject.prop;
    

    So maybe not using the optional chaining operator is better.

    Refer back to step 1: target-specific builds.

  • Reorder code. Example:

    const templateClone = template.content.cloneNode(true);
    this.container = templateClone.querySelector('.container');
    const shadowRoot = this.attachShadow();
    

    can be reordered like this:

    const templateClone = template.content.cloneNode(true);
    const shadowRoot = this.attachShadow();
    this.container = templateClone.querySelector('.container');
    

    which allows your minifier to collapse the variable declarations:

    const templateClone = template.content.cloneNode(true), shadowRoot = this.attachShadow();
    this.container = templateClone.querySelector('.container');
    
  • Delete unnecessary code.

  • Wrap optional code in environment variables. Examples:

    if (process.env.TEST_RUN) {
      component.testId = "testId";
    }
    
    if (process.env.NODE_ENV !== "production") {
      if (someAppStateThatShouldNeverOccur) {
        console.error("Detected development issue. Fix it!");
      }
    }
    

    During creation of the final bundle for production the code is transformed like so:

    if (false) {
      component.testId = "testId";
    }
    
    if (false) {
      if (someAppStateThatShouldNeverOccur) {
        console.error("Detected development issue. Fix it!");
      }
    }
    

    When your minifier sees code like this it omits it entirely.

  • Search the documentation of all your dependencies for these special environment variables. Example: if you’re using Sentry you can set the env var __SENTRY_DEBUG__ to false in production builds so that optional code is removed during minification.

  • Enable tree-shaking.

  • Ensure that your app’s package.json sets "sideEffects": false. Bundlers like Webpack, esbuild and bun agree.

  • Ensure that your dependencies have "sideEffects": false.

  • Ensure that the dependencies of your dependencies have "sideEffects": false.

  • Use ECMAScript Modules (ESM) and not CommonJS (CJS).

  • Ensure that all your dependencies use ECMAScript Modules (ESM) and not CommonJS (CJS).

  • Ensure that imports are consistent since inconsistent imports can lead to duplicate code.

  • Write services as plain ES modules that export functions since classes with public methods are not tree-shakable.

  • Avoid import * as Something since it’s not tree-shakable.

  • Enable name mangling (renaming basic identifiers like local variables, params, some functions).

  • Take name mangling to the next level. Rename private properties and methods. Rename exports. Rename as much internal code that you control as you can. Everything in this step is risky but should have a high return on investment.

  • If using TypeScript, prefer const enums to enums. const enums are inlined directly in the code, avoiding objects and imports. Example:

    // direction.ts
    export enum Direction {
      Up,
      Down,
    }
    
    // some-other-file.ts
    import { Direction } from './direction.ts'
    
    console.log(Direction.Up);
    

    gets transpiled to:

    // direction.ts
    export var Direction;
    (function (Direction) {
        Direction[Direction["Up"] = 0] = "Up";
        Direction[Direction["Down"] = 1] = "Down";
    })(Direction || (Direction = {}));
    
    // some-other-file.js
    import { Direction } from './direction.js'
    
    console.log(Direction.Up);
    

    while using a const enum would transpile to simply:

    console.log(0);
    
  • Optimize code at build-time. Example:

    export const ONE_HOUR_MS = 60 * 60 * 1000;
    export const ONE_DAY_MS = 24 * 60 * 60 * 1000;
    

    can be optimized to:

    export const ONE_HOUR_MS = 3600000;
    export const ONE_DAY_MS = 86400000;
    

    Libraries that can help with this: Prepack, preval.macro or babel-plugin-preval.

  • Serve JavaScript and (other text assets) compressed with Brotli / GZIP.


Finally, keep monitoring the size of your JavaScript bundle! Peacock’s CI measures the bundle size change of each PR and adds it as comment during code review. bundle-stats is one cool project that can help with this.

Also, something as simple as:

// src/index.js
export const UNUSED_EXPORT = 'THIS_SHOULD_NOT_BE_BUNDLED';

plus a CI test like:

grep -rq "THIS_SHOULD_NOT_BE_BUNDLED" dist

can go a long way in catching certain regressions.

In fact, now that I write this, I realise that awareness of your bundle size is actually the first step in this long journey. Optimization is an ongoing process, not a one-time task. Good luck!

P. S. – If you enjoyed the hand-drawn checkboxes I explain how to implement them in my post Web Component: Hand-drawn Checkbox.