0

If I have a file called index.js and it requires a couple of modules. Is there any way I can get a list of the modules that are required?

var _ = require("underscore")
var express = require("express")
var app = express()
return app

Then I have another file like this.

var listRequired = require("list-required")
listRequired("./index.js").then(function(moduleTypes){
  console.log(moduleTypes.npm) // ["underscore", "express"]
})

I'd really also like a way to track npm modules (ex. underscore), native node modules (ex. crypto, path) and local files (ex. ./routes.js)

So if index.js contained this:

var _ = require("underscore")
var express = require("express")
var routes = require("./routes")
var app = express()
module.exports = app

And routes.js contained this:

var crypto = require("crypto")
var Promise = require("bluebird")
module.exports = {}

Then I have another file like this.

var listRequired = require("list-required")/*(file, deepOption)*/
listRequired("./index.js", true).then(function(moduleTypes){
  console.log(moduleTypes.native) // ["crypto"]
  console.log(moduleTypes.local) // ["./routes"]
  console.log(moduleTypes.npm) // ["underscore", "express"]
})

Does this already exist in some capacity? ES6 import support would be nice as well.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

1 Answers1

1

The technique used to solve this kind of problem is called static analysis. You use something that parses source code and returns an abstract syntax tree. (This is very much like how a browser reads HTML and turns it into a DOM.)

Once you have an AST, it is relatively straightforward to walk the tree and look for interesting bits like require calls.

It looks like someone has already written a module that does exactly that, called required.

josh3736
  • 139,160
  • 33
  • 216
  • 263