--define
flag can be used with bun build
and bun build --compile
to inject build-time constants into your application. This is especially useful for embedding metadata like build versions, timestamps, or configuration flags directly into your compiled executables.
terminal
Why use build-time constants?
Build-time constants are embedded directly into your compiled code, making them:- Zero runtime overhead - No environment variable lookups or file reads
- Immutable - Values are baked into the binary at compile time
- Optimizable - Dead code elimination can remove unused branches
- Secure - No external dependencies or configuration files to manage
gcc -D
or #define
in C/C++, but for JavaScript/TypeScript.
Basic usage
With bun build
terminal
With bun build --compile
terminal
JavaScript API
Common use cases
Version information
Embed version and build metadata directly into your executable:Feature flags
Use build-time constants to enable/disable features:Configuration
Replace configuration objects at build time:Advanced patterns
Environment-specific builds
Create different executables for different environments:Using shell commands for dynamic values
Generate build-time constants from shell commands:Build automation script
Create a build script that automatically injects build metadata:Important considerations
Value format
Values must be valid JSON that will be parsed and inlined as JavaScript expressions:Property keys
You can use property access patterns as keys, not just simple identifiers:TypeScript declarations
For TypeScript projects, declare your constants to avoid type errors:Cross-platform compatibility
When building for multiple platforms, constants work the same way:Related
- Define constants at runtime - Using
--define
withbun run
- Building executables - Complete guide to
bun build --compile
- Bundler API - Full bundler documentation including
define
option