DEV Community

Cover image for 7 Practical Tips to Minimize Your JavaScript Bundle Size
Aleksei Berezkin
Aleksei Berezkin

Posted on

7 Practical Tips to Minimize Your JavaScript Bundle Size

Artwork: https://code-art.pictures/

Why Bother?

It might be surprising these days, but internet traffic is still an issue in many scenarios. Mobile networks often have limited data plans, device batteries are not infinite, and, most importantly, the user's attention while waiting for your site to load is limited. That's why bundle size still matters. Here are seven tips for you to consider.

1. Don't Transpile to ES5

In 2020, I was maintaining a promotional app for a local social network. It was a typical React + TypeScript + webpack application targeting ES5. When webpack 5 was released, I decided to upgrade. Everything went smoothly; I monitored error analytics and user feedback, and there was nothing unexpected. Only after a week did I accidentally discover that my bundle contained arrow functions — it was a new webpack feature.

Here's an excellent article about the state of ES5. Key takeaways:

  • Many libraries already contain ES6+ code, meaning bundles with them are not ES5-compatible.
  • Most of the world's popular sites are not ES5-compatible — your site might not need it either.
  • If you are certain you still need ES5 compatibility, you must include the libraries in your build process.

2. Know and Use Modern JavaScript Language Features

Here are some features that allow you to write better and more compact code.

2.1. Generators

Generators are an efficient way to traverse nested structures:

type TreeNode<T> = {
    left?: TreeNode<T>
    value: T
    right?: TreeNode<T>
};

function* traverse<T>(root: TreeNode<T>): Generator<T> {
    if (root.left) yield* traverse(root.left)
    yield root.value
    if (root.right) yield* traverse(root.right)
}
Enter fullscreen mode Exit fullscreen mode

2.2. Private Class Fields

Minifiers know for certain that these fields cannot have external usages, even in exported objects, and are free to shorten their names.

Source

export class A {
  #myFancyStateObject
}
Enter fullscreen mode Exit fullscreen mode

Bundle

export class A{#t}
Enter fullscreen mode Exit fullscreen mode

This won't work, of course, with TypeScript private fields, because the knowledge that they are private disappears once tsc has done its job.

2.3. Modern APIs

Have you heard about Promise.withResolvers() or Map.groupBy()? These APIs are not widely available at the time of this writing, but will be soon. Take a moment to familiarize yourself with them now and be ready to adopt them in a couple of years.

Tip: How to Discover New JavaScript APIs

There are countless blogs and podcasts, but I find the best “newsletters” are new .d.ts files in the TypeScript repository. Just open, for example, es2024.collection.d.ts and enjoy 🙂

3. Avoid Code Duplication

Do you notice the repeated pattern?

const clamp = (min, val, max) =>
  Math.max(min, Math.min(val, max))
const x = clamp(0, v1, a.length - 1)
const y = clamp(0, v2, b.length - 1)
const z = clamp(0, v3, c.length - 1)
Enter fullscreen mode Exit fullscreen mode

Repeated code not only increases the bundle size but also makes it harder to understand what each part does. This often leads developers to write new code instead of identifying and reusing existing utility functions, further bloating the bundle.

There's already a wealth of excellent material on this topic, so rather than retelling it, I recommend a classic: Refactoring by Martin Fowler. It covers not only simple examples like the one above but also complex cases such as coupled hierarchies and repeated designs.

Now, let's improve our small example. It seems clamp is often used to limit parameters to array index ranges, so we can create a shortcut:

const clampToRange = (n, {length}) =>
  clamp(0, n, length - 1)
const x = clampToRange(v1, a)
// ...
Enter fullscreen mode Exit fullscreen mode

This change makes it explicit that n is probably intended to be an integer, which isn't currently checked. It also highlights an unhandled edge case: empty arrays. By making this small deduplication, we also discovered two potential bugs 🙂

4. Avoid Overengineering

I don't remember the exact source of this saying, but I think it's spot on:

Overengineering is solving a problem that you don't have.

In the world of web development, I've observed two main types of overengineering.

4.1. Over-generalization

Consider this code. Paddings are multiples of 4px, and background colors are shades of blue. This is probably not a coincidence, and if so, it could indicate possible duplication. But do we really have enough information to extract the generic Button component, or are we overengineering?

CSS

.btn-a {
    background-color: skyblue;
    padding: 4px;
}
.btn-b {
    background-color: deepskyblue;
    padding: 8px;
}
Enter fullscreen mode Exit fullscreen mode

JSX

<button className='btn-a' onClick={handleClick}>
    Show
</button>
// ...
<button className='btn-b' onClick={handleSubmit}>
    Submit
</button>
Enter fullscreen mode Exit fullscreen mode

This advice does somewhat conflict with “Avoid duplication.” Over-deduplicating code can lead to overengineering. So, where do you draw the line? Personally, I use the magic number “3”: once I see three places with a similar pattern, it might be time to extract the generic component.

In the case of our blue buttons, I believe the best solution would be to use CSS variables, at least for padding, rather than creating a new component.

4.2. Using Improper Framework

Yes, I'm talking about what we love — Next.js, React, Vue, and so on. If your app doesn't involve a lot of interactivity at the level of DOM elements, or isn't dynamic, or is very simple, consider other options:

  • Static site generators — you can start with some curated lists.
    • Beware: some of them use React or other frameworks under the hood. If your goal is bundle minimization, try something different.
  • Content management systems, like WordPress.
  • Vanilla — especially useful in two cases:
    • The app is very simple.
    • The app doesn't manipulate much DOM but instead, for example, paints something on a canvas. I have a project exactly like this.

5. Avoid Dated TypeScript Features

The current goal of TypeScript is mainly type-checking JavaScript, but it wasn't always this way. Back in the pre-ES6 days, there were many attempts to create “better JavaScript,” and TypeScript was no exception. Some features date back to those early days.

5.1. Enums

Not only are they difficult to use properly, but they also transpile into quite verbose structures:

TypeScript

enum A {
  x, y
}
Enter fullscreen mode Exit fullscreen mode

JavaScript

var A;
(function (A) {
    A[A["x"] = 0] = "x";
    A[A["y"] = 1] = "y";
})(A || (A = {}));
Enter fullscreen mode Exit fullscreen mode

The official TypeScript Handbook recommends using simple objects instead of enums. You may also consider union types.

5.2. Namespaces

Namespaces were a pre-ESM modules solution. Not only do they increase the bundle size, but since namespaces are intended to be global, it becomes really hard to avoid naming conflicts in large projects.

TypeScript

namespace A {
  export let x = 1
}
Enter fullscreen mode Exit fullscreen mode

JavaScript

var A;
(function (A) {
    A.x = 1;
})(A || (A = {}));
Enter fullscreen mode Exit fullscreen mode

Instead of namespaces, use ES modules.

Note: Namespaces are still useful, however, for writing type definitions for global libs.

6. Don't Neglect Small Optimizations

Each of these small tricks can save you several to dozens of bytes in the bundle. If applied consistently, they can bring a visible result.

6.1. Use Truthy / Falsy Properties

For example, an empty string is falsy. To check if it's defined and non-empty, you can simply write:

if (str) {
  // str is non-empty
}
Enter fullscreen mode Exit fullscreen mode

6.2. Allow Non-strict Comparison Sometimes

I believe using == to coerce null to undefined, or vice versa, is totally justified.

if (value == null) {
  // value is null or undefined,
  // but not 0 or ''
}
Enter fullscreen mode Exit fullscreen mode

6.3. Use Nullish Coalescence, Logical OR, and Default Parameters to Substitute Default Values

// Replaces null, undefined and '' with 'e'
const v1 = str || 'e'

// Replaces null or undefined with ''
const v2 = str ?? ''

function doSth(str = '') {
  // str is '' if not passed
}
Enter fullscreen mode Exit fullscreen mode

6.4. Use Arrow Functions for One-liners

Instead of this:

function randomInt(bound) {
  return Math.floor(Math.random() * bound))
}
Enter fullscreen mode Exit fullscreen mode

Write this:

const randomInt = bound =>
  Math.floor(Math.random() * bound)
Enter fullscreen mode Exit fullscreen mode

6.5. Don't Use Classes for Very Simple Objects

Instead of this:

class User() {
  #name: string
  constructor(name: string) {
    this.#name = name
  }
  getName() {
    return this.#name
  }
}
Enter fullscreen mode Exit fullscreen mode

Write this:

type User = { name: string }
const user = {
  name: 'John Doe'
} satisfies User
Enter fullscreen mode Exit fullscreen mode

You may also freeze the object to protect its properties from changes.

7. Regularly Inspect Bundles

For each bundler, there are tools to visualize its content, such as webpack-bundle-analyzer for webpack and vite-bundle-analyzer for Vite. Tools like these help you identify common issues with your bundle:

  • A library takes up a disproportionate amount of space — maybe it's time to migrate or upgrade?
  • Two similar libraries are used in different parts of your project — can you consolidate and use only one?
  • A large file exists in your bundle but is only accessed by a page that 0.5% of users visit (e.g., a license text) — perhaps you can partition the bundle using dynamic import()?

In addition to these tools, it's a good idea to occasionally read through bundles manually to spot irregularities. For example, you might find ES5 helpers in an ES6+ bundle or CJS helpers in an ESM project due to TypeScript misconfiguration. These problems might not be caught by automated tools but can still increase loading time and potentially cost you your most valuable asset — the user's attention.


Thank you for reading. Happy coding!

Top comments (0)