Artwork: https://code-art.pictures/
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.
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:
Here are some features that allow you to write better and more compact code.
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) }
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 }
Bundle
export class A{#t}
This won't work, of course, with TypeScript private fields, because the knowledge that they are private disappears once tsc has done its job.
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.
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 ?
Do you notice the repeated pattern?
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) }
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:
export class A { #myFancyStateObject }
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 ?
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.
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
export class A{#t}
JSX
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)
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.
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:
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.
Not only are they difficult to use properly, but they also transpile into quite verbose structures:
TypeScript
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) }
JavaScript
export class A { #myFancyStateObject }
The official TypeScript Handbook recommends using simple objects instead of enums. You may also consider union types.
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
export class A{#t}
JavaScript
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)
Instead of namespaces, use ES modules.
Note: Namespaces are still useful, however, for writing type definitions for global libs.
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.
For example, an empty string is falsy. To check if it's defined and non-empty, you can simply write:
const clampToRange = (n, {length}) => clamp(0, n, length - 1) const x = clampToRange(v1, a) // ...
I believe using == to coerce null to undefined, or vice versa, is totally justified.
.btn-a { background-color: skyblue; padding: 4px; } .btn-b { background-color: deepskyblue; padding: 8px; }
<button className='btn-a' onClick={handleClick}> Show </button> // ... <button className='btn-b' onClick={handleSubmit}> Submit </button>
Instead of this:
enum A { x, y }
Write this:
var A; (function (A) { A[A["x"] = 0] = "x"; A[A["y"] = 1] = "y"; })(A || (A = {}));
Instead of this:
namespace A { export let x = 1 }
Write this:
var A; (function (A) { A.x = 1; })(A || (A = {}));
You may also freeze the object to protect its properties from changes.
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:
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!
The above is the detailed content of ractical Tips to Minimize Your JavaScript Bundle Size. For more information, please follow other related articles on the PHP Chinese website!