Course contentsShow
← JavaScript
Lesson 2451 of 2,72350. JavaScript Build ToolingFree lesson

Environment Variables and Build-Time Constants

How bundlers inject environment-specific values at build time, enabling different configs per environment.

Environment Variables and Build-Time Constants

You'll learn: how bundlers inject environment-specific values at build time to enable different configurations per environment without changing your source code.

The Problem

You often need different values in different environments—maybe an API endpoint for development (http://localhost:3000) versus production (https://api.example.com), or feature flags that toggle on staging but not production. Hardcoding these means risky edits before each deployment.

Build-Time Injection

Modern bundlers solve this by replacing special placeholders with actual values during the build process. Your source code references variables like process.env.API_URL, and the bundler substitutes the appropriate literal value based on which environment you're building for.

Think of it like mail-merge: you write {{NAME}} once, and the tool fills in "Alice" or "Bob" depending on the recipient. Here, the bundler fills in different values depending on the target environment.

How It Works

When you run a build command (e.g., npm run build:production), the bundler:

  1. Reads environment variables from your shell, .env files, or configuration
  2. Finds references to those variables in your code (like process.env.NODE_ENV)
  3. Replaces them with string literals (like "production")
  4. Performs dead code elimination—if a condition is now always false, that branch gets removed entirely

The result? Your production bundle contains only the code and values for production, no development tools or staging URLs.

Why Build-Time?

Because the substitution happens during bundling, not at runtime, you get:

  • Smaller bundles (unused code paths removed)
  • Better performance (no runtime checks)
  • Security (sensitive dev-only values never ship to clients)

Key Takeaway: Bundlers replace environment-specific placeholders with actual values at build time, creating optimized, environment-specific bundles without runtime overhead or manual code changes.