File structure: submodules required in Node.js

I have the following Node.js / 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.jsthrough the module name (because I installed it as the main entry point file in package.json) as follows:

var myModule = require('myModule');

I would like to require a submodule (as in the AMD template):

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

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

Assuming that the following structure will be present:

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

Now execution require('myModule/submodules/submodule1')will work.

: /config, " " , , , require('myModule/dist/node/submodules/submodule1')?

+4
1

: .

: , (/myModule/submodules/), - API (index.js), .

require('myModule/some/complex/path'), Node.js/npm , require('myModule').

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

:

var myModule = require('myModule');
var submodule1 = myModule.require('submodules/submodule1');
+8

Source: https://habr.com/ru/post/1606581/


All Articles