Last active
December 22, 2016 14:33
-
-
Save jescalan/11016226 to your computer and use it in GitHub Desktop.
lazy-loading require in node
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
/** | |
* Requires a library, but only loads it when it's actually used. | |
* | |
* lazy_require('fs'); | |
* fs.readFileSync('example.js'); | |
* | |
* var wow = lazy_require('fs'); | |
* wow.readFileSync('example.js'); | |
* | |
* @param {String} lib - name of the lib you want to load | |
* @param {String} name - name of the var you want to assign the lib to, defaults to lib name | |
* @return {*} a getter for the library you wanted to load | |
*/ | |
lazy_require = function(lib, name){ | |
if (!name) name = lib; | |
this.__defineGetter__(name, function(){ return require(lib) }); | |
return this[name] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment