9

I have the following Node.js module/npm package:

|- dist/
|- - requirejs/
|- - - [stuff in amd pattern ...]
|- - node/
|- - - index.js
|- - - submodules/
|- - - - submodule1.js
|- - - - [submodule2.js etc.]
|- package.json
|- README.md

I can require dist/node/index.js via the module name (because I set it as the main entry-point file in package.json) like so:

var myModule = require('myModule');

I would like to require the submodule (as in AMD pattern) by doing so:

var mySubmodule = require('myModule/submodules/submodule1');

This throws an error in Node.js. The problem is, that Node.js requires the main file from its dist/node/ subdirectory but still keeps the modules root as the working directory.

Assuming the following structure would be present:

|- dist/
|- - node/
|- - - index.js
|- submodules/
|- - submodule1.js
|- package.json
|- README.md

Now doing require('myModule/submodules/submodule1') would work.

NOW THE QUESTION: Is there any setting/config to set the "module namespace" or working directory to the directory where the main file is in, or do I really need to put the submodules folder into the project root, to make it accessible without doing require('myModule/dist/node/submodules/submodule1')?

2 Answers 2

10

Short answer: you can't.

Long answer: You should either directly use the second directory structure you proposed (/myModule/submodules/) or add some kind of API to your main exports (index.js) to quickly get the desired module.

While you can technically call require('myModule/some/complex/path'), the Node.js / npm packages standard is to rely on the unique interface provided by require('myModule').

// /dist/node/index.js
var path = require('path');
exports.require = function (name) {
  return require(path.join(__dirname, name));
};

Then in your app:

var myModule = require('myModule');
var submodule1 = myModule.require('submodules/submodule1');
Sign up to request clarification or add additional context in comments.

2 Comments

require('myModule') does not return a module object (or maybe at least not anymore)
At least require('fs/promises') has now become a canonical "my/complex/path"
0

You now can do something like this using the exports feature of Node.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.