config-bark
v2.1.4
Published
A simple and opinionated config file loader.
Downloads
18
Readme
config-bark 🐶
Make your config files bark at you.
This is a dead simple config file loader that looks for files here:
project-root/config/[environment].json
where [environment]
is passed by you falling back to process.env.NODE_ENV
or development
by default.
Usage
Install it with yarn or npm:
yarn add config-bark
Add the appropriate JSON config file(s) to your project.
Use config values in your code:
import config from 'config-bark';
// Optional: call __load__ once in the entry point for your app so it knows where to look for config files
// it will try to autoload config files if it can detect where to look
config.__load__(__dirname);
console.log(config.db.host('fallback'));
Details
You can chain as many properties as you need to without fear of the dreaded
TypeError: Cannot read property 'foo' of undefined.
When you're ready to get the value, just call it like a function. Optionally pass in
a fallback value to use if the given config value doesn't exist. If no fallback is
provided and the value doesn't exist undefined
will be returned.
Remember, that you can't access any value just by referencing it. You need to call the last item in the chain to actually return the value.
Say goodbye to this:
if (config && config.db && config.db.credentials) {
console.log(config.db.credentials.password);
}
Now you can do this:
console.log(config.db.credentials.password());
API
config.__load__({string} startingDir, {string} environment)
- startingDir: A full path to start from when looking for the project root dir (where the config
folder should be stored). We walk up the directory tree from this point looking for a directory that
has both a
node_modules
directory and apackage.json
file in it. If no such directory is found an error is thrown. - environment: Optional: What config file to load instead the config directory. If nothing is
passed, this will default to
process.env.NODE_ENV
ordevelopment
if that is undefined.
Webpack Caveat
When autoloading config files (or if no environment is passed to __load__()
), this will use
process.env.NODE_ENV
to determine which file to load. If you're like me and you use webpack to
manage your NODE_ENV
variable, this can present a problem. So, in projects that use config-bark
I have this in my webpack.config.js:
const nodeExternals = require('webpack-node-externals');
{
// ...
externals: [nodeExternals({ whitelist: ['config-bark'] })];
// ...
}
If you don't use webpack or you don't use webpack-node-externals
or you are diligent about
setting NODE_ENV
appropriately everywhere your code runs, you shouldn't have to worry about
this caveat.