headacheCoder
headacheCoder

Reputation: 4613

File Structure: Requiring Sub-Modules in Node.js

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')?

Upvotes: 9

Views: 7612

Answers (2)

Remirror
Remirror

Reputation: 754

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

Upvotes: 0

Crogo
Crogo

Reputation: 493

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');

Upvotes: 10

Related Questions