Guide
Installation
| 1 | npm install @xpulse/config --registry=https://npm.xpulse.one |
Quickstart
| 1 | import config from '@xpulse/config'; |
| 2 | |
| 3 | await config.load(); |
| 4 | |
| 5 | console.log(config.name); |
| 6 | console.log(config.get('http.port')); |
What Happens on Load?
config.load() runs the following steps in order:
dotenv.load() β loads .env + .env.{NODE_ENV} into process.env
- Read and parse
xpulse.json
- Validate
name β throws if missing
- Apply defaults β missing standard keys are filled with fallback values
- Resolve
${VAR} β all references to process.env values are replaced
- Emit
config:loaded
Creating xpulse.json
Every project needs an xpulse.json in the repo root:
| 1 | { |
| 2 | "name": "xpulse-web", |
| 3 | "type": "tool" |
| 4 | } |
name is required β all other keys are optional and have defaults.
${ENV_VAR} References
Values in xpulse.json can reference .env variables:
| 1 | { |
| 2 | "name": "xpulse-web", |
| 3 | "type": "tool", |
| 4 | "http": { |
| 5 | "port": "${PORT}" |
| 6 | }, |
| 7 | "sources": { |
| 8 | "chat": { |
| 9 | "url": "${CHAT_URL}" |
| 10 | } |
| 11 | } |
| 12 | } |
| 1 | |
| 2 | PORT=3000 |
| 3 | CHAT_URL=https://chat.xpulse.one |
| 1 | await config.load(); |
| 2 | config.get('http.port') |
| 3 | config.get('sources.chat.url') |
Unresolvable variables remain as ${VAR} and produce a warning.
Custom Keys
xpulse.json is an open schema β custom keys are allowed and
passed through without warnings:
| 1 | { |
| 2 | "name": "xpulse-chat", |
| 3 | "type": "tool", |
| 4 | "release": { |
| 5 | "current": "1.3.0", |
| 6 | "codename": "Abomasnow" |
| 7 | } |
| 8 | } |
| 1 | config.get('release.current') |
| 2 | config.get('release.codename') |
Events
After config.load(), config:loaded is emitted via @xpulse/event.
dotenv:loaded is fired shortly before by @xpulse/dotenv.
| 1 | import event from '@xpulse/event'; |
| 2 | |
| 3 | event.on('config:loaded', ({ name, type, env, files }) => { |
| 4 | console.log(`${name} (${type}) loaded β ENV: ${env}`); |
| 5 | }); |
| 6 | |
| 7 | await config.load(); |
Explicit Path
| 1 | |
| 2 | await config.load({ path: '/app' }); |
| 3 | |
| 4 | |
| 5 | await config.load({ env: 'stage' }); |