Skip to content

Instantly share code, notes, and snippets.

@menixator
Created December 26, 2014 16:57
Show Gist options
  • Save menixator/69e4140d575c7eb84552 to your computer and use it in GitHub Desktop.
Save menixator/69e4140d575c7eb84552 to your computer and use it in GitHub Desktop.
Code snippet to find the dependencies of a CoffeeScript file.
// Finding all the require calls in coffee-script file.
// This won't work if a minified version of coffeescript is loaded.(Like @ http://coffeescript.org)
// Note that if the argument to require should be a string. `module = 'fs'\nfs = require(module)` wont work.
var CoffeeScript = require('coffee-script');
// There are two requires calls.
var code = 'fs = require \'fs\'\nEventEmitter = require(\'events\').EventEmitter';
var program = CoffeeScript.nodes(code);
var deps = [];
program.traverseChildren(false, function(node) {
var type = node.constructor.name;
if (type === 'Call' &&
node.variable.base.value === 'require' &&
node.variable.properties.length === 0
) {
var arg = node.args.slice(0, 1).pop();
var strTest = arg.base.value.match(/^['"](.*)['"]$/);
if (arg.properties.length === 0 && strTest !== null) {
deps.push(strTest[1]);
}
}
});
console.log("The coffe-script code snippet depends on: \'", deps.join(' , '), '\'');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment