如何让父模块导入NodeJS中子模块的子模块 [英] How to let parent module to import a child module of the child module in NodeJS

查看:382
本文介绍了如何让父模块导入NodeJS中子模块的子模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在开发模块B.但是我知道模块C将在模块A中用require('Module C')调用.我遇到的错误是Cannot find module 'Module C'.

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:

在模块B的index.js中

In index.js of Module B

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

在模块A中

require('Module_B').Module_C

我希望有更好的方法.

推荐答案

模块不会继承.

如果您需要在系统中的两个不同位置使用同一模块,只需在两个不同的位置使用它即可.

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

如果您试图在一个模块中提供多个模块的功能,那么您正在寻找的是一项服务,您将为其创建API,以抽象化您希望最终用户能够实现的功能为此,您需要从所有需要触摸的地方进行操作.

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.

这篇关于如何让父模块导入NodeJS中子模块的子模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆