Last active
December 22, 2015 05:39
-
-
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).
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
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