skip to content

Bundling & Transpiling

Every web build resolves a module graph, lowers syntax for its browser targets, serves hot updates in development and emits maps. Interviewers probe why a build breaks.

on this pageshow

explore

questions

30

In a web build, what does `import thumbUrl from './specimen-thumb.png'` give your code, and when does the bundler inline the image instead?

level: juniorimportance: must knowfreq 24%

answer

  1. a generated module stands in
  2. default export is a string
  3. emitted copy under a new name
  4. a size threshold decides
  5. data URL inside the importer

basics

~20 s

The import becomes a small generated module whose default export is a URL string pointing at a copy of the image the build emits. Files below a size threshold are often inlined instead, as a base64 data URL inside the importing file.

solid answer

~40 s

A bundler's module graph is made of JavaScript, so it turns `specimen-thumb.png` into a tiny generated module whose default export is the URL the image will be served from. During development that URL points at the source file; in the production build the bundler copies the file into its output, usually under a content-hashed name, and your code receives that final URL. Files under a size threshold, typically a few kilobytes, can be inlined instead: the export becomes a `data:` URL that carries the bytes in base64. Inlining saves a request, but the bytes grow by about a third, ride inside the importing JavaScript or CSS file, are downloaded again whenever that file changes, and get no cache entry of their own. A `url()` in an imported stylesheet goes through the same emit-or-inline decision.

code

javascript · 9 lines
javascript
import thumbUrl from './specimen-thumb.png'   // 48 KB photo
import pinUrl from './icons/map-pin.png'       // 600-byte icon

// development: a dev-server URL that maps to the source file
// production:  thumbUrl === '/assets/specimen-thumb.3f9a1c2e.png'
// production:  pinUrl   === 'data:image/png;base64,iVBORw0KGgo...'

document.querySelector('#thumb').src = thumbUrl
document.querySelector('#pin').src = pinUrl

go deeper

for a junior

Remember that an image import gives you a URL string, not the image. In production that URL points at a copy the build emitted, not at your source file.

for a middle

Explain the generated module, the emit-or-inline decision by size threshold, and that url() in imported CSS follows the same rule. Know the base64 overhead.

for a senior

Weigh inlining by caching, not just request count: an inlined asset is re-sent with every change to its importer. Spot production-only bugs caused by code that bypasses the import.

for a principal

Treat the inline threshold as a shared default with caching and size consequences across apps, and decide when teams may override it per file rather than globally.

## What the import actually is A bundler's **module graph** is built from JavaScript modules, so every node it ships must end up as JavaScript. When it meets `import thumbUrl from './specimen-thumb.png'`, it does not put a picture into your code. It replaces the image with a small **generated module** whose only job is to export a value. For images, fonts, video and other binary files, that value is a **URL string**: ```js // what the generated module amounts to export default '/assets/specimen-thumb.3f9a1c2e.png' ``` Your code then does whatever it would do with any URL: assigns it to `img.src`, passes it to a component, or builds a CSS background from it. The browser downloads the file the normal way, as a separate request. Key properties of this model: - The import is **resolved at build time**, so a missing or misspelt file fails the build instead of producing a broken image in production. - The URL is **whatever the build decides**: during development it usually points at the source file, and in the production build it points at the copy the build wrote. - `url()` references inside an imported stylesheet are treated the same way, so a `background: url('./fern.png')` is emitted or inlined and rewritten exactly like a JavaScript import. ## Emitting a file For anything above the inline threshold, the bundler **emits** the file: it copies it into the output folder, usually with a content hash in the name, and makes the generated module export the URL of that copy. Two consequences follow: 1. The deployed site serves the file from the build output, not from your source tree, so only files the graph reached are there. 2. The file gets its own HTTP cache entry, independent of the JavaScript that references it. Why a hash in the name helps caching is a separate topic; here it only matters that the URL is computed by the build. A variable font referenced from an `@font-face` rule is normally emitted this way: it is far above any inline threshold, and a font inlined into a stylesheet would make the stylesheet itself heavy. How the browser then loads and swaps fonts is its own subject. ## Inlining below a threshold Small files, such as the museum's 600-byte map-pin icon, can instead be **inlined**: the generated module exports a `data:` URL that contains the file's bytes, typically base64-encoded. Build tools pick their own default threshold, usually a few kilobytes, and let you change it or force the choice per file. | | Emitted file | Inlined data URL | |---|---|---| | What the import exports | URL of a separate file | `data:image/png;base64,...` string | | Network requests | One more request for the file | None for the asset itself | | Size on the wire | Original bytes | About one third larger before compression | | Caching | Its own cache entry | Cached only as part of the importing file | | When the importing code changes | Asset stays cached | Asset bytes are downloaded again | Inlining is a trade, not a free win: - It **saves a request**, which matters most for tiny files and less on connections that multiplex many requests. - It **moves bytes into the importer**, making that JavaScript or CSS file larger and slower to arrive before it can run or apply. - It **ties the asset's caching to the importer**: every release that touches the importing chunk re-sends the icon, even if the icon never changed. ## Other output forms of the same idea The generated module does not have to export a URL. The same mechanism can expose a file's **raw text** as a string, which is how an SVG sprite's markup or a shader source can be inserted into the page. Tools usually make that an explicit opt-in per import, because "give me the URL" and "give me the contents" are different contracts for the same file. JSON and WebAssembly files have their own module forms, covered separately. ## Why this breaks only in production The usual production-only failures come from code that bypasses the import: - A **hard-coded path string** to a source image works when a dev server serves the source tree, but the build never saw it, so no file is emitted. - Code that **assumes a file name** (for example by string-concatenating `specimen-thumb.png`) misses the name the build actually emitted. - Code that expects an `http` URL and receives a `data:` URL, for example to derive a file name from it, breaks only for files small enough to be inlined. The rule that avoids all three: let the import hand you the URL, and treat that URL as opaque.

  • Why not inline every image to save requests?
    Base64 makes the bytes about a third larger, and they move into the importing JavaScript or CSS file, which grows and arrives later. The asset also loses its own cache entry: whenever the importing chunk changes, the inlined image is downloaded again even though it did not change. Inlining pays off only for small, rarely changing files.
  • How would you get the text of an SVG sprite instead of its URL?
    Ask the build for the file's contents rather than its URL. The same generated-module mechanism then exports a string holding the markup, which you can insert into the document. Tools expose this as an explicit opt-in per import, because the URL form and the text form are different contracts for the same file.
  • What does the build do with `url('./fern.png')` inside an imported stylesheet?
    It treats the reference as a dependency of the stylesheet: it resolves the file, emits or inlines it under the same threshold rule as a JavaScript import, and rewrites the `url()` so it points at the result from wherever the emitted stylesheet ends up.

  • Importing an image always puts the image bytes into the JavaScript bundle.
  • The imported variable holds the source path exactly as it was written.
  • Inlining is always faster because it removes a network request.
  • A data URL gets its own cache entry, like a separate file.
  • Only JavaScript files can take part in the module graph.
open as a page

In a web dev server, what is hot module replacement, and how does it differ from a live reload of the page?

level: juniorimportance: must knowfreq 26%

basics

~20 s

Hot module replacement swaps only the edited modules into the running page, so in-memory state such as a half-typed form can survive; a live reload requests the whole page again and re-runs every script, losing that state.

open as a page

In a web build, what is a module graph, and how does a bundler build one starting from an entry point?

level: juniorimportance: must knowfreq 24%

basics

~20 s

A module graph is every file an app needs, linked by its imports. A bundler starts at each entry, resolves each specifier to one file, parses that file for further imports and repeats until no new file appears.

open as a page

In a web build, what is a source map for, and how do browser developer tools find the map for a shipped file?

level: juniorimportance: must knowfreq 24%

basics

~20 s

A source map is a JSON file that maps positions in shipped, transformed code back to the original file, line, column and name. Developer tools find it through a sourceMappingURL comment at the end of the file or a SourceMap response header.

open as a page

What separates syntax lowering from a polyfill in a web build, and which one fixes `stop?.platform` versus `departures.at(-1)` on an older browser?

level: juniorimportance: must knowfreq 24%

basics

~20 s

Lowering rewrites newer syntax, such as optional chaining, into older equivalent code at build time; a polyfill ships runtime code that defines a missing built-in, such as Array.prototype.at. Neither can add an engine capability like Proxy.

open as a page

In a web build, how does build-time constant replacement turn `__COLLECTION_API__` into shipped code, and why must a string value be wrapped in `JSON.stringify`?

level: middleimportance: must knowfreq 16%

basics

~20 s

The build finds each occurrence of the registered identifier or member expression and swaps in the value as source code. A string must arrive with its own quotes, which JSON.stringify adds, or it becomes a bare identifier.

open as a page

In hot module replacement, how does a dev server decide whether an edit is swapped in place or turns into a full page reload?

level: middleimportance: must knowfreq 20%

basics

~20 s

The dev server walks up from the edited module through its importers until each path reaches an accept boundary, a module that declared it can take the update; if any path reaches the entry without one, the page reloads.

open as a page

In a web build, why does a browser bundle receive a package's server file when its `exports` map lists `import` before `browser`?

level: middleimportance: must knowfreq 14%

basics

~20 s

A resolver walks the exports entry's keys in the package's own order and takes the first condition it has active. A browser build importing with import has both import and browser active, so the earlier import key wins.

open as a page

When a web build emits source maps, how do inline, external and hidden maps differ in what reaches the browser, and when does each fit?

level: middleimportance: must knowfreq 15%

basics

~20 s

An inline map is a data URL inside the shipped file, so every user downloads it. An external map is a separate file the comment names. A hidden map is that file emitted without the comment, so nothing points at it.

open as a page

In a web build, how does a bundler resolve `'./utils'` and `'date-lib'` to files, and why would a browser's native module loader reject both?

level: juniorimportance: should knowfreq 15%

basics

~20 s

A relative specifier is joined to the importer's folder and tried as written, then with each configured extension, then as a folder's index file. A bare one is looked up in node_modules folders, climbing upward. Browsers do neither.

open as a page

In a web build, why does `new URL('./decoder.wasm', import.meta.url)` keep working after bundling, while `new URL(fileName, import.meta.url)` breaks?

level: middleimportance: should knowfreq 9%

basics

~20 s

With a literal path, bundlers recognise the pattern, emit the file and rewrite the URL to the emitted copy. With a variable, the build cannot tell which file is meant, so the code ships unchanged and resolves against the chunk's new location.

open as a page

In a web build, why does a path string to an image under `src/` 404 in production, and how does a public pass-through folder differ?

level: middleimportance: should knowfreq 12%

basics

~20 s

A path string is not an import, so the build never emits the file and the source folder is not deployed. A public folder is copied verbatim to the site root, but nothing checks that referenced files exist.

open as a page

How does a bundling dev server differ from an unbundled native-ESM dev server, and where does each pay its cost as an app grows?

level: middleimportance: should knowfreq 17%

basics

~20 s

A bundling dev server builds the whole module graph before serving, so start-up grows with the app; an unbundled server transforms each module when the browser requests it, so start-up stays fast but page loads grow with the modules imported.

open as a page

Why does an unbundled dev server pre-bundle third-party dependencies before serving them, and what makes it redo that work?

level: middleimportance: should knowfreq 10%

basics

~20 s

Pre-bundling converts CommonJS or UMD packages into ES modules the browser can import, and collapses packages built from hundreds of internal files into one module; the result is cached and rebuilt when its inputs, such as the lockfile, change.

open as a page

In a web build, how do the `main`, `module` and `browser` package fields pick a file, and what does a `browser` mapping to `false` do?

level: middleimportance: should knowfreq 9%

basics

~20 s

Without an exports map, a browser build checks a priority list of fields, typically browser, then module, then main. An object-form browser field replaces modules for that package's imports, and false swaps a module for an empty one.

open as a page

In a source map, what do the `sources`, `sourcesContent`, `names`, `mappings` and `ignoreList` fields hold, and how is `mappings` encoded?

level: middleimportance: should knowfreq 10%

basics

~10 s

sources lists original files, sourcesContent their optional full text, names original identifiers, ignoreList the indices of third-party sources. mappings is a string of Base64 VLQ deltas: semicolons separate generated lines, commas separate segments.

open as a page

How does a browser-target query or a Baseline target decide what a web build lowers and polyfills, and what changes when you move it?

level: middleimportance: should knowfreq 12%

basics

~20 s

The target resolves to minimum browser versions; the transpiler lowers only syntax some listed browser lacks and the polyfill step adds only missing built-ins. An older floor means more rewritten code, more polyfills and larger bundles.

open as a page

What may a minifier rename or remove in a production web build, and why does a check like `err.constructor.name === 'FareError'` start failing?

level: middleimportance: should knowfreq 10%

basics

~20 s

By default a minifier renames local bindings, including function and class names, and strips whitespace, comments and usually debugger statements; it keeps property names and exported names. Renaming a class changes its name property, so name-based checks fail.

open as a page

How does a usage-based polyfill injector choose what a web build adds, and why can it miss a method called through a computed property?

level: middleimportance: should knowfreq 8%

basics

~20 s

It scans each file it compiles for references to built-ins the target browsers lack, matched by name, and adds an import for each. A call like stopsmethod names no method in the source, so nothing is injected for it.

open as a page

In a web build where each component imports its own stylesheet, why can CSS rules apply in a different order in production than in development?

level: seniorimportance: should knowfreq 8%

basics

~20 s

Production builds extract imported CSS into one file per chunk, and a lazy chunk's file is inserted when that chunk loads. At equal specificity the later stylesheet wins, so the winner depends on load and navigation order rather than on development's order.

open as a page

After several hot module replacement swaps, a self-accepting chart module polls its API once more per swap and loses its buffered data points; why, and what fixes it?

level: seniorimportance: should knowfreq 8%

basics

~20 s

A self-accepting module re-runs on every swap: each new instance starts another timer while the old ones keep running, and module-scope variables start empty. A cleanup callback must stop the old timer and hand the buffer to the next instance.

open as a page

In a component framework's hot swap, why does editing a file that exports both a component and a constant reset state that other edits keep?

level: seniorimportance: should knowfreq 12%

basics

~20 s

A state-keeping swap works only when every export is a component the runtime can swap by identity; importers hold a constant directly, so the tooling hands the update on to them, and the tree they render can remount or the page reloads.

open as a page

In a web build in a workspace monorepo, why can resolving a linked package to its real path load a second copy of a shared dependency, and how do you fix it?

level: seniorimportance: should knowfreq 7%

basics

~20 s

After following the link, the shared package's files resolve bare imports from its real folder, where a copy installed inside the package, if any, is found first. Keep one physical copy, or resolve that dependency from the app root.

open as a page

Why would a build's source maps point at transpiled JavaScript instead of the TypeScript files when a hotel-booking app transpiles, bundles and minifies, and how do you fix it?

level: seniorimportance: should knowfreq 5%

basics

~20 s

Each stage maps only its own input to its output, so the final map reaches the TypeScript only if every stage reads the previous map and emits a composed one. A stage that drops it makes its own input the new original.

open as a page

A security review finds a hotel-booking app's source maps publicly reachable; what do `sourcesContent`, `sources` and `names` reveal, and how do you keep maps private yet useful?

level: seniorimportance: should knowfreq 8%

basics

~20 s

Public maps make the original code readable: sourcesContent holds every file's full text with comments, sources the project's file layout and names its original identifiers. Keep them off the public deploy, or behind access control, while internal tools still read them.

open as a page

When is a second legacy build worth it over one web build lowered for everyone, if the app must also run on older kiosk browsers?

level: seniorimportance: should knowfreq 6%

basics

~20 s

A second legacy build pays off when old browsers are a small but required share: modern browsers keep the lean modern bundle and only kiosks download the lowered, polyfilled copy. Otherwise one lowered build is simpler to ship and test.

open as a page

In a web build, how does importing a JSON file differ from the browser's native JSON module, and when should large JSON be fetched instead?

level: middleimportance: nice to knowfreq 5%

basics

~20 s

Natively, with { type: 'json' } is required and the module has one default export. A bundler compiles the JSON into the importing chunk, often allowing named imports; large or changing data is better emitted as a file and fetched.

open as a page

Why would a development build emit source maps that are line-only or eval-wrapped rather than column-accurate, and what does each shortcut cost?

level: middleimportance: nice to knowfreq 6%

basics

~20 s

Both trade accuracy for rebuild speed. A line-only map keeps one mapping per line, so it is smaller and quicker to build but loses columns. Eval-wrapped modules carry their own maps, so a rebuild only regenerates the edited module's map.

open as a page

In a web build, when an ES module imports a CommonJS-only package, what does the bundler emit for that package, and when does its code run?

level: seniorimportance: nice to knowfreq 5%

basics

~20 s

A bundler typically wraps the CommonJS module's body in a function that receives exports and module, and emits a small helper that runs it once, on the first require or import, caching module.exports for every later caller.

open as a page

Why are class decorators a lowering hazard in a TypeScript web build, and how do legacy and standard decorators differ at runtime?

level: seniorimportance: nice to knowfreq 4%

basics

~20 s

The same @decorator syntax has two incompatible meanings: legacy decorators receive a target, key and descriptor, standard ones a value and a context object. Builds must lower the right flavour, and some fast transformers cannot lower standard decorators yet.

open as a page