Env Config Precedence Resolver

Resolve configuration from defaults file environment and CLI args with explicit precedence and type coercion.

JavascriptConfig Management

Code

javascriptsnippet
1 line
export function resolveConfig({defaults={},file={},env=process.env,args={}}={}){const merged={};for(const[key,defaultVal]of Object.entries(defaults)){const raw=args[key]??env[key.toUpperCase()]??file[key]??defaultVal;merged[key]=coerce(raw,defaultVal);}return merged;}function coerce(value,ref){if(typeof ref==='number')return Number(value);if(typeof ref==='boolean')return value==='true'||value===true;if(typeof ref==='object'&&ref!==null)return JSON.parse(value);return String(value);}

How the snippet works

The working surface is the functions resolveConfig and coerce — everything else is wiring.

What to watch for

  • The guard typeof ref==='number' short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is export function resolveConfig({defaults={},file={},env=process.env,args={}}={})

resolveConfig is the public entry point; everything else in the file exists to support it.

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `resolveConfig`, `coerce` at load time.