Last active
January 5, 2018 19:59
-
-
Save AmrAbdulrahman/92fb422c222580b3e6dcc2db6ef5f328 to your computer and use it in GitHub Desktop.
Forward all files as modules from a directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
It's often we have a bunch of modules that we need to just forward | |
from a single entry point | |
as following: | |
-- src | |
---- utils | |
------ isFunction.js | |
------ isString.js | |
------ isArray.js | |
Sometimes we need to create a single centeric entry point that groups all the modules as 'utils' | |
so that we can use it as following | |
const { isFunction, isArray } = require('./utils'); | |
To do so, we have to create 'utils/index.js' and manually export a one-to-one map | |
as following: | |
module.exports = { | |
isFunction: require('./isFunction'), | |
isString: require('./isString'), | |
isArray: require('./isArray'), | |
}; | |
When we create a new util function, we have to manually add it in the index.js | |
What this following script does that it constructs this mapping automatically in run-time | |
*/ | |
const path = require('path'); | |
const fs = require('fs'); | |
module.exports = (basePath) => { | |
return fs | |
.readdirSync(basePath) // read all files in the directory | |
.map(file => file.replace('.js', '')) // remove the file extention | |
.filter(file => file !== '*' && file !== 'index') // exclude '*.js' and 'index.js' | |
.reduce((exports_, module_) => { // construct the map | |
const modulePath = path.join(basePath, module_); | |
exports_[module_] = require(modulePath); | |
return exports_; | |
}, {}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = require('path-to-forward.js')(__dirname); | |
/* | |
this is exactly equivelent to: | |
module.exports = { | |
a: require('./a'), | |
b: require('./b'), | |
c: require('./c'), | |
d: require('./d'), | |
e: require('./e'), | |
... | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment