Modules and Namespaces
Config Namespace
Group configuration values by mode.
config-namespace
Namespace-style objects can group constants as well as functions. A mode key selects the value needed for the current run.
Config Namespace
config_namespace.js
Replay: real traced execution (multi-file project)
const mode = "dev";
const host = {
dev: "localhost",
test: "staging",
prod: "api",
}[mode];
const url = "https://" + host + ".example.com";
console.log("mode=" + mode);
console.log("url=" + url);
const mode = "test";
const host = {
dev: "localhost",
test: "staging",
prod: "api",
}[mode];
const url = "https://" + host + ".example.com";
console.log("mode=" + mode);
console.log("url=" + url);
const mode = "prod";
const host = {
dev: "localhost",
test: "staging",
prod: "api",
}[mode];
const url = "https://" + host + ".example.com";
console.log("mode=" + mode);
console.log("url=" + url);
mode ← dev, host ← localhost, { dev: "localhost", test: "staging", prod: "api", }[mode] ← localhost
1const mode→ dev = "dev"; //@mode="test", "prod"2const host→ localhost = {3 dev: "localhost",4 test: "staging",5 prod: "api",6}[modedev];7const url→ https://localhost.example.com = "https://" + host→ localhost + ".example.com";89console.log("mode=" + modedev);10console.log("url=" + urlhttps://localhost.example.com);outputmode=dev url=https://localhost.example.comvalues this steplocalhost{ dev: "localhost", test: "staging", prod: "api", }[mode]
mode ← test, host ← staging, { dev: "localhost", test: "staging", prod: "api", }[mode] ← staging
1const mode→ test = "test";2const host→ staging = {3 dev: "localhost",4 test: "staging",5 prod: "api",6}[modetest];7const url→ https://staging.example.com = "https://" + host→ staging + ".example.com";89console.log("mode=" + modetest);10console.log("url=" + urlhttps://staging.example.com);outputmode=test url=https://staging.example.comvalues this stepstaging{ dev: "localhost", test: "staging", prod: "api", }[mode]
mode ← prod, host ← api, { dev: "localhost", test: "staging", prod: "api", }[mode] ← api
1const mode→ prod = "prod";2const host→ api = {3 dev: "localhost",4 test: "staging",5 prod: "api",6}[modeprod];7const url→ https://api.example.com = "https://" + host→ api + ".example.com";89console.log("mode=" + modeprod);10console.log("url=" + urlhttps://api.example.com);outputmode=prod url=https://api.example.comvalues this stepapi{ dev: "localhost", test: "staging", prod: "api", }[mode]
Follow the Mode
modestarts asdev.- The lookup object has keys
dev,test, andprod. - Bracket lookup reads the value at
dev. hostbecomeslocalhost.- The URL becomes
https://localhost.example.com. | mode | host value | printed URL | | --- | --- | --- | | dev | localhost | https://localhost.example.com | | test | staging | https://staging.example.com | | prod | api | https://api.example.com |
Exercise: config_namespace.js
Reproduce mode=dev and url=https://localhost.example.com, then use modes test and prod to predict the staging and api URLs.