Node.js module.exports 的用途是什么,你如何使用它?

2022-01-30 00:00:00 node.js javascript

Node.js module.exports 的用途是什么以及如何使用它?

我似乎找不到任何关于此的信息,但它似乎是 Node.js 的一个相当重要的部分,因为我经常在源代码中看到它.

根据 Node.js 文档:p><块引用>

模块

对当前的引用模块.特别是 module.exports与导出对象相同.看src/node.js 了解更多信息.

但这并没有真正的帮助.

module.exports 究竟做了什么,一个简单的例子是什么?

解决方案

module.exports 是作为 require 调用的结果实际返回的对象.

exports 变量最初设置为同一个对象(即,它是别名"的简写),因此在模块代码中您通常会这样写:

让 myFunc1 = function() { ... };让 myFunc2 = function() { ... };出口.myFunc1 = myFunc1;出口.myFunc2 = myFunc2;

导出(或公开")内部作用域函数 myFunc1myFunc2.

在调用代码中你会使用:

const m = require('./mymodule');m.myFunc1();

最后一行显示 require 的结果如何(通常)只是一个可以访问其属性的普通对象.

注意:如果您覆盖 exports,那么它将不再引用 module.exports.因此,如果您希望将新对象(或函数引用)分配给 exports,那么您还应该将该新对象分配给 module.exports

<小时>

值得注意的是,添加到 exports 对象的名称不必与您要添加的值的模块内部范围名称相同,因此您可以:

让 myVeryLongInternalName = function() { ... };出口.shortName = myVeryLongInternalName;//根据需要添加其他对象、函数

接着是:

const m = require('./mymodule');m.shortName();//调用 module.myVeryLongInternalName

What is the purpose of Node.js module.exports and how do you use it?

I can't seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code.

According to the Node.js documentation:

module

A reference to the current module. In particular module.exports is the same as the exports object. See src/node.js for more information.

But this doesn't really help.

What exactly does module.exports do, and what would a simple example be?

解决方案

module.exports is the object that's actually returned as the result of a require call.

The exports variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:

let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;

to export (or "expose") the internally scoped functions myFunc1 and myFunc2.

And in the calling code you would use:

const m = require('./mymodule');
m.myFunc1();

where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed.

NB: if you overwrite exports then it will no longer refer to module.exports. So if you wish to assign a new object (or a function reference) to exports then you should also assign that new object to module.exports


It's worth noting that the name added to the exports object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:

let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required

followed by:

const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName

相关文章