国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial ractical Tips to Minimize Your JavaScript Bundle Size

ractical Tips to Minimize Your JavaScript Bundle Size

Dec 31, 2024 am 01:39 AM

ractical 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)
}

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

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

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

See all articles