None of the 100 config libraries on npm did what I wanted... so i created my own. Works a little bit like the wonderful rust config crate. Goals of this projects include
- no dependencies
- treat the config like an object, not a key value store
- be able to set default values
- merge config from json file at a given path, this is optional
- merge env var's with a namespace. Allow nesting object values with underscores. Do a best effort conversion of the data type ('false' => boolean)
- validate the configuration based on a given schema
$ yarn add objconf
schema after loading
const Config = ; let conf = ; conf; // assume config.json = { c: 67890 } conf; // export PROJECT_A_B = 'something else' conf; conf; let config = conf; console; // => 'something else' console; // => 67890
schema before loading
const Config = ; let conf = ; conf; conf // only merges env vars 'A', 'B', and 'C' conf
API
constructor(options)
options.preserveCase
: default `false, dont convert keys and prefix's to lowercase
set_schema(obj)
set the config objects schema
conf;
merge_defaults(obj)
merge configuration with a given object
conf;
merge_file(filepath, required=false)
merge configuration from a json file given its path. When required is false, any error on reading the file will be suppressed. set required to true
to raise those errors.
conf; // suppresses errors, good for local dev configconf; // raises errors
merge_env(prefix = '')
given environment variables with the given prefix. The env var names by default are converted to lowercase for comparrison and merging into the configuration. So for example the env var PREFIX_PARENT_CHILD=test
will be merged into the config at { parent: { child: 'test' } }
. Prefix is optional, if you do not give one its suggested to add a schema before running this method.
conf; // run set_schema() first!conf;
validate(schema = this.schema)
takes a schema which is an object with string values. These values can be 'string', 'boolean', 'null ', 'undefined', or 'number'. if the types of the current configuration do not match the schema, an error is thrown. If you have set the schema already you do not need to pass one in
conf; conf;
conf; ... conf
get()
return a copy of the configuration object
conf;console
Development
Issues and PR's are always welcome, just follow the prettier.js style guides described below.
Testing
this project uses ava, just run yarn test
(or npm test
if your into that sort of thing). Test's are good examples on how to use this package
Styling
This project uses Prettier.js for code formating and linting. I would recomend installing it globally as described here and integrate it with your editor.
here is the configuration used
--no-semi: false
--single-quote: true
--tab-width: 4
--print-width: 100
check out .eslint.rc
as well