Search code examples
node.jsmodulerequire

How do I use require inside a module with the parents context?


app.js

require('./modules/mod');

modules/mod/mod.js

modules.exports = () => {
   require('./modules/secondmodule');
}

Essentially I want the above code to be able to require modules, but using the same context that itself was called from, e.g. another module in the same folder, without having to use relative paths.

I thought module.require() did this, but it seems to give me the same error that require() was after I moved my code into the separate module (mod.js).

edit:

I have since discovered I can use require.parent.module and it seems to be working. Please let me know if this is not advised.


Solution

  • require uses paths that are relative to current module. It's possible to do this by providing require from parent module:

    modules.exports = parentRequire => {
       parentRequire('./modules/secondmodule');
    }
    

    Which is used like:

    require('./modules/mod')(require);
    

    It's correct to use relative modules instead because child module shouldn't be aware of the context in which it's evaluated:

    require('../secondmodule');
    

    In case mod has to be decoupled from secondmodule, dependencies can be provided to it with some common pattern, e.g. dependency injection or service locator.