Menu

1 / 2

How a JavaScript Bundler Works

DEV Community: esbuild·Alysaa Lissy·about 19 hours ago
#g6v6RA10
#devtoesbuild#devto#dev#import#const
Reading 0:00
15s threshold

TL;DR

A bundler starts at an entry file , follows every import to build a dependency graph , then packs the modules into one or a few files.

The output is mostly an object of module functions plus a ten-line runtime with a cache . That is the whole trick.

Tree shaking, code splitting, minification and hashing are optimizations on the same graph .

Below is a 60-line working bundler , checked against native modules and esbuild.

1. What a bundler does, and when you can skip it

You give a bundler one entry file . It follows every import , collects every file it reaches, and writes them into the file or files you ship.

Do you need one? A small app does not. Browsers run ES modules natively with <script type="module"> . Three things push real projects toward bundling anyway:

Import specifiers are not URLs. import x from './utils' and import React from 'react' work in Node and in bundlers, but a browser needs a full file path, and bare names like react need an import map.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.