10

Lets say the module X has a Y submodule. From my node app that has a dependency on X, how can I require submodule Y?

var Y = require('X:Y'); results in Cannot find module 'X:Y'

1
  • 1
    Can you expand on why you want to do this? Generally this is frowned upon unless module X is explicitly exporting module Y. Commented Feb 19, 2014 at 5:36

2 Answers 2

19

Submodule meaning an export from within the X module?

Try...

require('X/path-to-Y')
11

It's better to just declare Y as your own dependency. But if you really want to do that, here is how it's done:

// make sure that module X is loaded into a cache
require('X')

// get this module from cache
var module_X = require.cache[require.resolve('X')]

// require submodule Y
var Y = module_X.require('Y')
1
  • Ironically, this is what I needed (I needed programmatic access to the internal Traceur interpreter for my project, which was only otherwise available through the command line). It at least gave me access to the directory to run a child process for it.
    – Claudia
    Commented Aug 11, 2014 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.