Nested Module
A module can be stored within either another module or a folder. In this case, its name will be prepended with a namespace that is actually a chain of its ancestor modules/folders, separated by dots. For example:
When:
app
|- index.js
|- modules
| |- db
| | |- mysql
| | | |- meta.js
| | | |- index.js
| | |- mongodb
| | | |- meta.js
| | | |- index.js
| |- log
| | |- meta.js
| | |- index.js
| | |- file-based
| | | |- meta.js
| | | |- index.js
Then:
var db = $('db'); // undefined
var mysql = $('db.mysql'); // mysql module.
var mongodb = $('db.mongodb'); // mongodb module.
var log = $('log'); // log module.
var fileBasedLog = $('log.file-based'); // file-based log module.
This mechanism also brings you an ability to switch between modules. For example, given you have two different configuration sets, one for production and one for development. You can defineconfig
as a module with two sub-modules:production
anddevelopment
, and then set the active config to your prefered module.
your-app
|- index.js
|- modules
| |- config
| | |- meta.js
| | |- index.js
| | |- development
| | | |- meta.js
| | | |- index.js
| | |- production
| | | |- meta.js
| | | |- index.js
Config:
// meta.js
modules.exports = {
use: ['config.development'], // sets active config to development.
singleton: true
}
// payload.js
module.exports = (active) => active; // returns active config
Development:
// meta.js
module.exports = {
// leave as empty.
}
// payload.js
module.exports = {
DB_HOST: 'localhost',
DB_NAME: 'mydb'
// and other settings...
}
Usage:
var config = $('config');
var dbHost = config.DB_HOST; // 'localhost'
var dbName = config.DB_NAME; // 'mydb'
Last updated