项目作者: pyramidjs

项目描述 :
Smart configuration control
高级语言: JavaScript
项目地址: git://github.com/pyramidjs/configure.git
创建时间: 2017-12-02T06:02:31Z
项目社区:https://github.com/pyramidjs/configure

开源协议:MIT License

下载


Configure

Master Build

Smart configuration control

Install

  1. npm i @pyramid/configure

Basic Usage

This package by default read the config folder in your working directory:

  • config
    • app.json
    • database.json
    • language.json
  1. const config = require("@pyramid/configure");
  2. console.log(config.app.name);
  3. console.log(config.database.mysql.host);
  4. console.log(config.language.supported[0]);

If folder config does not exist, file config.json will be checked instead.

  • config.json
  1. {
  2. "app": {
  3. "name": "MY APP"
  4. }
  5. }
  1. const config = require("@pyramid/configure");
  2. console.log(config.app.name);

You can override the config file path with an environment variable:

  1. // read a folder
  2. process.env.CONFIG_FILE=src/config
  3. // read a file
  4. process.env.CONFIG_FILE=src/config.json
  5. // with absolute path
  6. process.env.CONFIG_FILE=/path/to/src/config.json

If you specified a single file, the config object will be the file itself rather than a nested object with the filename as its key(like folder reading does).

src/config.json

  1. {
  2. "app": {
  3. "name": "myapp"
  4. }
  5. }
  1. process.env.CONFIG_FILE = src / config.json;
  2. const config = require("@pyramid/configure");
  3. console.log(config.app.name);

It won’t be loaded again once done. To reload configs, you need to call:

  1. // delete cached config
  2. config.__.desolve();
  3. // reload
  4. config = require("@pyramid/configure");

Env File

By default, This package read a .env file in your working directory and get environment variables from this file.

  1. NODE_ENV=production
  2. CONFIG_FILE=src/config.json

You may override this behaviour by passing the following environment variable:

  1. process.env.ENV_FILE=src/.env
  2. const config = require('@pyramid/configure');

You may optionally set ENV_INJECT to inject env file variables into process.env.

Existing environment variables won’t be overrided.

  1. process.env.ENV_INJECT=true
  2. NODE_ENV=development npm start
  1. # NODE_ENV won't be set because it already exists
  2. NODE_ENV=production
  3. CONFIG_FILE=src/config.json

Smart Config File

A bunch of keywords can be used in config files

  1. {
  2. "name": {
  3. "$env": "APP_NAME"
  4. },
  5. "database": {
  6. "port": {
  7. "$env": ["DB_PORT", 3306]
  8. },
  9. "host": {
  10. "$env": ["DB_HOST", "localhost"]
  11. },
  12. "username": {
  13. "$env": "DB_USER"
  14. },
  15. "password": {
  16. "$env": ["DB_PASS", { "$env": "DB_USER" }]
  17. }
  18. }
  19. }

The $env object reads environment varaibles with an optional fallback value. With the following env set:

  1. APP_NAME=myapp
  2. DB_HOST=10.10.10.100
  3. DB_USER=admin

The loaded config will be

  1. {
  2. "name": "myapp",
  3. "database": {
  4. "port": 3306,
  5. "host": "10.10.10.100",
  6. "username": "admin",
  7. "password": "admin"
  8. }
  9. }

Here is a list of available keywords:

$env

Get value from environment variables(first try env file, then process.env) with an optional fallback value

  • params: string|[string, any]
  • returns any

$path

Resolve the path to absolute from current working directory

  • params: string
  • returns string

$file

Resolve the path and read the file with an optional encoding

  • params: string|[string, string]
  • returns string|Buffer

$json

Parse the given string into object

  • params: string
  • returns any

$number

Parse the given string into a number

  • params: string
  • returns number

$concat

Concat strings or arrays

  • params: string[]|[][]
  • returns string|any[]

$max

Return the max number in the array

  • params: number[]
  • returns number

$min

Return the min number in the array

  • params: number[]
  • returns number

$sum

Sum the numbers in the array

  • params: number[]
  • returns number

$avg

Return the average value of the array

  • params: number[]
  • returns number

$first

Return the first element in the array

  • params: any[]
  • returns any

$last

Return the last element in the array

  • params: any[]
  • returns any

$at

Return element in the array at the given index

  • params: [any[], number]
  • returns any

$asce

Sort the numbers in ascending order

  • params: number[]
  • returns number[]

$asce

Sort the numbers in descending order

  • params: number[]
  • returns number[]

$rand

Return an element at random index

  • params: any[]
  • returns any

$rands

Return the given amount of elements at random indices

  • params: [any[], number]
  • returns any[]

$reverse

Reverse an array

  • params: any[]
  • returns any[]

$slice

Slice an array from the given index to an optional end index

  • params: [any[], number]|[any[], number, number]
  • returns any[]

$count

Return the length of an array

  • params: any[]
  • returns number

$merge

Return the merge of two objects

  • params: [any, any]
  • returns any

$keys

Return the keys of an object

  • params: any
  • returns string[]

$vals

Return the values of an object

  • params: any
  • returns any[]

$zip

Merge a series of key-value pairs into an object

  • params: [any, any][]
  • returns any

$zap

Split an object into key-value pairs

  • params: any
  • returns [any, any][]

$cond

Return the second or third element based on the boolean value of the first element

  • params: [boolean, any, any]
  • returns any

$and

Return true only if both two elements’ boolean values are true

  • params: [boolean, boolean]
  • returns boolean

$or

Return true if any of the two elements’ boolean value is true

  • params: [boolean, boolean]
  • returns boolean

$not

Return true only if the given value is false

  • params: boolean
  • returns boolean

$true

Return true if the given value is true or ‘true’(case insensitive) or 1 or ‘1’

  • params: boolean|string
  • returns boolean

$null

Return true if the given value is null or undefined

  • params: any
  • returns boolean

$undefined

Return true only if the given value is undefined

  • params: any
  • returns boolean

$type

Return true only if the given value is of the given type

  • params: [any, string]
  • returns boolean

$test

Return boolean test result(!!) of the given value

  • params: [any, string]
  • returns boolean

Other Keywords

Operators

$abs, $add(+), $sub(-), $mul(*), $div(/), $mod(%), $ceil, $floor, $round, $trunc, $sign

Comparers

$gt(>), $gte(>=), $lt(<), $lte(<=), $eq(===), $eqv(==), $ne(!==), $nev(!=), $in, $ni

String Morph

$upper, $lower, $snake, $pascal, $camel, $dash, $plural, $singular

Utils

A utils is attached to each config instance. You can acces it by the getter __:

  1. // make a deep cloned copy
  2. const copy = config.__.clone(obj);
  3. // merge target object's copy into source object's copy deeply
  4. const merged = config.__.merge(source, target);
  5. // load environment variables, optionally inject them into process.env
  6. const envs = config.__.env("./.env", true);
  7. // parse config by json string
  8. let conf = config.__.resolve(
  9. JSON.parse(fs.readFileSync("./config.json", "utf8"))
  10. );
  11. // load config by path(absolute or relative to working directory)
  12. conf = config.__.load("./config.json");
  13. // delete config referenced cache(the next time you reference this module, config file will be reloaded)
  14. config.__.desolve();

You can also use utils without the config instance:

  1. const utils = require("@pyramid/configure/utils");
  2. // NOTE: utils.desolve will be undefined

Webpack

To integrate into webpack, there is a built-in plugin:

  1. const ConfigurePlugin = require("@pyramid/configure/utils/webpack");

webpack.config.js

  1. plugins: [
  2. new ConfigurePlugin({
  3. filename: path.resolve(__dirname, "path/to/config.json")
  4. })
  5. ];

And import that config in your modules:

index.js

  1. import * as config from "./path/to/config.json";

You may add a resolve alias to shorten the import:

webpack.config.js

  1. resolve: {
  2. alias: {
  3. config: path.resolve(__dirname, 'path/to/config.json')
  4. }
  5. },

index.js

  1. import * as config from "config";

NOTE

By default the json config is loaded as string. It’s also compatible with file-loader. If conflicts occur, you may need to bypass the specific loader(s) with include/exclude filters. e.g.

  1. {
  2. test: /\.json$/,
  3. exclude: /\/config\.json$/,
  4. use: 'some-loader'
  5. }

Test

  1. npm test

License

See License