Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Require Module of a Node Submodule

Tags:

node.js

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'

like image 572
Branka Avatar asked Feb 18 '14 23:02

Branka


People also ask

Where does require look for modules?

The require function will look for files in the following order. NPM Modules. It will look in the node_modules folder.

Are Node modules required?

Answer for Do I need Node_modules in production React? No, You don't need to push your node_modules folder to production whether it is a static export or dynamic build. When you export a static build the source file is converted into HTML & js files. So there is no need for node modules on production env.

Should I use import or require?

Require is Non-lexical, it stays where they have put the file. Import is lexical, it gets sorted to the top of the file. It can be called at any time and place in the program. It can't be called conditionally, it always run in the beginning of the file.


2 Answers

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')
like image 52
alex Avatar answered Nov 03 '22 02:11

alex


Submodule meaning an export from within the X module?

Try...

require('X/path-to-Y')
like image 39
Peter Avatar answered Nov 03 '22 03:11

Peter