skip to content

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%

answer

  1. text in, text out
  2. identifier or dotted member expression
  3. the value is source code
  4. quotes must be inside the value
  5. destructuring escapes the match

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.

solid answer

~40 s

Constant replacement is a build-time rewrite: you register a key such as `__COLLECTION_API__` or `process.env.DEBUG_PANEL` with a value, and every matching identifier or member expression in the code is replaced by that value **as JavaScript source**. So the value must be a valid expression. A string supplied as `'staging'` is pasted as the code `staging`, a reference to a variable that does not exist, and the bundle throws `ReferenceError` at runtime; `JSON.stringify('staging')` yields `"staging"`, quotes included. Booleans, numbers and objects are usually serialised for you. Matching is syntactic, so `const { DEBUG_PANEL } = process.env` or `process.env[name]` is not replaced and fails in the browser. Some dev servers provide the constants as real globals during development and only substitute text in the build, which is why such bugs can show up only in production.

code

javascript · 11 lines
javascript
// values given to the build's constant replacer:
//   __COLLECTION_API__ -> JSON.stringify('https://collections.example.org/v2')
//   __DEBUG_PANEL__    -> JSON.stringify(false)

// source
fetch(`${__COLLECTION_API__}/sites`)
if (__DEBUG_PANEL__) mountDebugPanel()

// emitted, before minification
fetch(`${"https://collections.example.org/v2"}/sites`)
if (false) mountDebugPanel()

go deeper

for a junior

Recall that the build swaps the constant's name for its value as code before shipping, so string values need JSON.stringify to keep their quotes.

for a middle

Explain syntactic matching of identifiers and member expressions, why destructured or computed access is missed, and why some unmatched forms work only in development.

for a senior

Diagnose production-only ReferenceErrors from unreplaced constants, and add a post-build check that no registered key survives in the output.

for a principal

Standardise how constants are named, stringified and read across shared configuration, so one convention prevents the silent-miss class of bug in every app.

## What the mechanism is **Build-time constant replacement** lets a build bake values into the code it ships. You give the build a table of keys and values; the build parses each module and replaces every occurrence of a key with its value before the code is minified and emitted. - A **key** is an identifier (`__COLLECTION_API__`) or a dotted member expression (`process.env.DEBUG_PANEL`). - A **value** is source text: it is inserted where the key was, as if you had typed it there. - The result is ordinary code. Nothing is looked up at runtime; the constant simply no longer exists in the output. This is how the museum viewer gets its collection API address and its debug-panel flag without any runtime configuration request. ## Why a string needs `JSON.stringify` Because the value is pasted as code, a string must carry its own quotes. `JSON.stringify` produces exactly that: a valid JavaScript string literal, with quotes and escaping. | Value supplied for `__COLLECTION_ENV__` | `console.log(__COLLECTION_ENV__)` becomes | What happens | |---|---|---| | `JSON.stringify('staging')`, i.e. `"staging"` | `console.log("staging")` | Logs the string | | `'staging'` | `console.log(staging)` | `ReferenceError: staging is not defined` | | `'https://collections.example.org/v2'` | not a valid expression | Rejected by the build, or broken code | | `true` | `console.log(true)` | Non-string values are usually serialised for you | | `'window.__collectionApi'` | `console.log(window.__collectionApi)` | Deliberate: an expression read at runtime | Two points in this table catch people out: 1. Tools usually **serialise non-string values** (booleans, numbers, objects) automatically. Only strings are taken literally as code, because a string is also how you pass an intentional expression, as in the last row. 2. The failure mode depends on the value. A word becomes a stray identifier that throws at runtime; a URL is not a valid expression at all, so the build either rejects it or emits code that does not parse. ## What the replacer matches, and what it misses Replacement works on the **syntax** of the code, not on values at runtime. It matches the exact identifier or member-expression shape registered, and nothing that merely computes the same value: - `if (process.env.DEBUG_PANEL === 'true')` is replaced, because the member expression matches; - `const { DEBUG_PANEL } = process.env` is **not** replaced, because the code reads the parent object and destructures it; - `process.env[flagName]` is **not** replaced, because a computed property cannot be matched at build time; - a misspelt key, such as `__COLLECTON_API__`, is not an error either: it is left in the code and throws when it runs. In the browser there is no `process` object unless something provides one, so the unreplaced forms throw `ReferenceError` instead of quietly reading a value. ## Why it can break only in production Some dev servers do not substitute text during development; they provide the registered constants as real global values and perform the textual replacement only in the production build. Under that model, an access the replacer cannot match may still find a value in development and then fail after the build. When a constant works locally and is undefined in production, check how the code reaches it before suspecting the build configuration. ## What follows from replacement Once the build has replaced a flag, the code contains a literal condition such as `if (false)`. A later minification step can then remove that branch entirely; when and why that removal succeeds is a separate topic about dead code. Two other neighbours to keep apart: - Anything replaced is **shipped in plain text** to every visitor. Which values may be inlined at all is a separate decision. - The type checker does not know about replaced constants unless they are declared, and declaring them does not provide a value; typing them is a separate subject. ## A checklist for adding a constant 1. Choose a key that cannot collide with real code, such as a double-underscore name. 2. Wrap every string value in `JSON.stringify`. 3. Read the constant only through the exact registered expression. 4. Build once and search the output for the key: any surviving occurrence is a runtime error waiting to happen.

  • Why does `const { DEBUG_PANEL } = process.env` throw in the browser even though the key is registered?
    The replacer matches the exact expression `process.env.DEBUG_PANEL`. Destructuring reads `process.env` as an object and picks the property at runtime, so no matching expression exists in the source and nothing is replaced. In the browser `process` is usually undefined, so the read throws `ReferenceError`. Read the constant through the registered expression instead.
  • When would you pass a string value without `JSON.stringify` on purpose?
    When you want an expression evaluated at runtime instead of a literal, for example `'window.__collectionApi'`, so the shipped code reads a value the hosting page sets. The value is still pasted as code; it is just code you meant to write.
  • How do you check that every constant was replaced?
    Build, then search the emitted files for each key. A key that survives was read through a form the replacer did not match, or was misspelt, and will throw at runtime. The search is cheap and catches what neither the build nor a development run reports.

  • A replaced constant is a global variable the production bundle reads at runtime.
  • A plain string value gets its quotes added automatically.
  • Destructuring the parent object still gets each property replaced.
  • An unmatched or misspelt constant makes the build fail.
  • If a constant works in the dev server, the build must replace it too.