Skip to content

Instantly share code, notes, and snippets.

@RReverser
Last active December 22, 2015 05:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RReverser/6425375 to your computer and use it in GitHub Desktop.
Save RReverser/6425375 to your computer and use it in GitHub Desktop.
Node.js part description with automatic resolving dependencies by names in argument list (like AngularJS does).
function part(name, exec, deps) {
console.log(name + '...');
var code = exec.toString();
if (deps) {
exec = new Function(deps, 'return(' + code + ')()');
} else {
deps =
code
.match(/\((.*?)\)/)[1]
.split(', ')
.filter(Boolean)
;
}
return exec.apply(this, deps.map(function (name) {
return require(name.replace(/[A-Z]/g, function (c) { return '-' + c.toLowerCase() }));
}));
}
// Usage:
part('Checking configuration', function (path) {
// path === require('path') here
});
part('Minifying', function (uglifyJs) {
// uglifyJs === require('uglify-js') here
// (since argument names can't contain dashes and npm anyway allows only lowercase package names)
})
part('Publishing', function (npm, child_process) {
// npm === require('npm'), child_process === require('child_process') here
});
part('Sample for potentially minified script', function () {
// fs === require('fs'), http === require('http') here
}, ['fs', 'http']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment