简体   繁体   English

NodeJS-如何正确导出模块

[英]NodeJS - how to export a module correctly

Given two modules a and b . 给定两个模块ab I know that it is possible to expose a 's functionality to another module using the module.exports . 我知道这是可能的暴露a的功能,使用其他模块module.exports I probably do not use it correctly. 我可能没有正确使用它。

a.js a.js

function A() { ... }
A.prototype.func = function() { ... }

function test() {
    new A().func();
}

test();
module.exports = {
    A : new A()
};

The test() is working correctly. test()正常工作。 But the following breaks: 但是有以下突破:

b.js b.js

var A = require("./a");
A.func(); //throws an exception

How do I export the whole A module with its functionality? 如何导出整个A模块及其功能?

Update: executing console.log(A) over b (as a second line), does not reveal any of A 's methods and variables. 更新:b执行console.log(A) (作为第二行),不显示A的任何方法和变量。

Try this: 尝试这个:

module.exports = new A();

You won't be able to instantiate a new A in b, but it seems like that's what you want. 您将无法在b中实例化一个新的A ,但这似乎就是您想要的。

Edit: 编辑:

Or you could change b.js to: 或者,您可以将b.js更改为:

var A = require('./a');
A.A.func();

But this is likely not what you want. 但这可能不是您想要的。

The idea is that whatever exports is will be what is returned from require . 这个想法是,无论exports是什么,都将是require回报。 It's exactly the same reference. 这是完全相同的参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM