简体   繁体   English

node.js模块/导出系统:是否可以将模块作为功能导出

[英]node.js module/export system: is it possible to export a module as a function

I want to do something like this in Dispatch.js 我想在Dispatch.js中做类似的事情

function handle(msg) {
    ....
}
exports = handle;

and this in the calling index.js 这在调用index.js中

var dispatch = require("./Dispatch);
dispatch("data");

Any ideas? 有任何想法吗?

exports = handle

This creates a local variable called exports . 这将创建一个名为局部变量exports This is different from overwriting module.exports . 这与覆盖module.exports不同。

module.exports = handle

This overwrites the exports variable that lives in module scope, this will then be read by require . 这将覆盖位于模块范围内的export变量,然后将由require读取。

In the browser window["foo"] and foo are the same, however in node module["foo"] and foo behave subtly different. 在浏览器中, window["foo"]foo相同,但是在节点module["foo"]foo行为略有不同。

The local variable scope context and module are not the same thing. 局部变量作用域上下文和module不是同一件事。

Do: 做:

function handle(msg) {
    ....
}
module.exports = handle;

and it works the way you want. 它以您想要的方式工作。

The problem behind this issue ( exports vs module.exports vs exports.something ) is best described in this article: 这背后的问题的问题( exports VS module.exports VS exports.something )在这篇文章中是最好的描述:

http://www.alistapart.com/articles/getoutbindingsituations http://www.alistapart.com/articles/getoutbindingsituations

The first version ( exports = handle ) is exactly the problem: the missing binding that is mandatory in javascript: 第一个版本( exports = handle )正是问题所在:缺少的绑定在javascript中是必需的:

exports = handle means window.exports = handle (or whatever node.js has as the global object) window.exports = handle exports = handle表示window.exports = handle (或任何node.js作为全局对象的)

Another way of seeing the problem is thinking about how node could load your module: 解决问题的另一种方法是考虑节点如何加载模块:

function loadModule(module, exports) {

inside here comes your module code 里面有你的模块代码

}

If your code overwrites the exports parameter ( exports = handle ), this change is not visible from the outside of this function. 如果您的代码覆盖了exports参数( exports = handle ),则此更改从此函数的外部是不可见的。 And for this overwriting one can use the module object. 为此,可以使用module对象。

The problem would not occur if exports would be a variable visible in the scope where the function body is. 如果exports是在函数体所在范围内可见的变量,则不会发生此问题。

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

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