How to let parent module to import a child module of the child module in NodeJS

笑着哭i 提交于 2020-01-07 02:22:30

问题


Module A
│
└─ Module B (devDependency in Module A's package.json)
   │
   └─ Module C (dependency in Module B's package.json)

Module B is what I am developing. But I know that module C would be called in Module A with require('Module C'). And the error I am having is Cannot find module 'Module C'.

My current solution is ugly which is:

In index.js of Module B

exports.Module_C = require('Module_C) || require(path.resolve(__dirname, 'node_modules/Module_C/index');

In Module A

require('Module_B').Module_C

I am hoping there is better way to do it.


回答1:


Modules are not inherited.

If you need the same module in two different places in your system, just require it in two different places.

// A.js
var C = require("./modules/c");
var B = require("./modules/b");


// B.js
var C = require("./modules/c");
module.exports = { };

// C.js
module.exports = { };

If you need to import subsections of a module, then navigate to the file (or root of the files) that you need.

// app.js
var add = require("./lib/helpers/math/add");

If you are trying to offer the functionality of multiple modules inside of one module, then what you're looking for is a service, which you will create an API for, to abstract what you want the end user to be able to do, from all of the places you need to touch, in order to do it.

Even if that service / library is basically just extending other interfaces onto its own interface.



来源:https://stackoverflow.com/questions/38086744/how-to-let-parent-module-to-import-a-child-module-of-the-child-module-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!