Here is a neat approach inspired by this article. It does not require any additional packages except the ubiquitous lodash package. Moreover, it lets you manage nested defaults with environment-specific overwrites.
First, create a config folder in the package root path that looks like this
package
|_config
|_ index.js
|_ defaults.json
|_ development.json
|_ test.json
|_ production.json
here is the index.js file
const _ = require("lodash");
const defaults = require("./defaults.json");
const envConf = require("./" + (process.env.NODE_ENV || "development") + ".json" );
module.exports = _.defaultsDeep(envConf, defaults);
Now let's assume we have a defaults.json like so
{
"confKey1": "value1",
"confKey2": {
"confKey3": "value3",
"confKey4": "value4"
}
}
and development.json like so
{
"confKey2": {
"confKey3": "value10",
}
}
if you do config = require('./config')
here is what you will get
{
"confKey1": "value1",
"confKey2": {
"confKey3": "value10",
"confKey4": "value4"
}
}
Notice that you get all the default values except for those defined in environment-specific files. So you can manage a config hierarchy. Using defaultsDeep
makes sure that you can even have nested defaults.