Search code examples
node.jsnpmrequire

Can a npm dependency require a module from its parent package


I am building a server app as a "core" framework and (potentially) multiple specialisations, starting with "spec_a".

I would like "core" to be an npm package, and "spec_a" to be an npm package which requires "core".

While I could require spec_a's modules and pass them to core in function calls, I would prefer core to read a config file and try to require modules (which are specified in the config file) from it's parent package. (The core shouldn't need to know the name of its parent package, as it will be different from each specialisation.)

What I am looking for is a require_from_parent(module_name_from_config) call.

Is there a way of making such a thing?

I was thinking of using require('../'+module_name_from_config), but this is fragile and will probably break on the latest npm.


Solution

  • I think I found the answer here on a nodebb blog.

    var Topics = module.parent.require('./topics'),
        User = module.parent.require('./user'),
        Notifications = module.parent.require('./notifications');