Last active
January 23, 2019 16:27
-
-
Save VitalyKondratiev/4b7dc12f18f2be73b92424bd672ecbdb to your computer and use it in GitHub Desktop.
Loading modules from NPM at runtime
This file contains hidden or 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
dl_require(['beauty', 'moment']).then(_modules => { | |
/* Demo data end */ | |
var beauty = _modules.beauty; | |
var moment = _modules.moment; | |
beauty.beautifyConsole(); | |
console.log('log:', 'you can put your code here'); | |
console.info('info:', moment().format("dddd, MMMM Do YYYY, h:mm:ss a")); | |
/* Demo data end */ | |
}); | |
function dl_require(module_names) { | |
return new Promise(function (resolve, reject) { | |
var modules = {}; | |
var missing_modules = []; | |
module_names.forEach(module_name => { | |
try { | |
modules[module_name] = require(module_name); | |
} | |
catch (ex) { | |
missing_modules.push(module_name) | |
} | |
}); | |
if (missing_modules.length) { | |
var child = require('child_process').exec('npm i ' + missing_modules.join(' '), { stdio: [0, 1, 2] }, function (err, stdout, stderr) { | |
if (err) | |
throw (stderr); | |
missing_modules.forEach(module_name => { | |
modules[module_name] = require(module_name); | |
}); | |
resolve(modules); | |
}); | |
child.stdout.on('data', function (data) { | |
console.log(data.toString()); | |
}); | |
} | |
else { | |
resolve(modules); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment