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) }
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 }
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.
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?
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 ?
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
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.
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
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.
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
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.
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:
const clampToRange = (n, {length}) => clamp(0, n, length - 1) const x = clampToRange(v1, a) // ...
6.2. Allow Non-strict Comparison Sometimes
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; }
6.3. Use Nullish Coalescence, Logical OR, and Default Parameters to Substitute Default Values
<button className='btn-a' onClick={handleClick}> Show </button> // ... <button className='btn-b' onClick={handleSubmit}> Submit </button>
6.4. Use Arrow Functions for One-liners
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 = {}));
6.5. Don't Use Classes for Very Simple Objects
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.
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!
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
