Expressjs JavaScript Fundamentals: exports = module.exports

Expressjs JavaScript Fundamentals: exports = module.exports = createApplication;

本文关键字:exports module JavaScript Fundamentals Expressjs      更新时间:2023-09-26

我不知道这个模式叫什么,如果我知道的话我会直接去查。

主要是如何工作的?(这段代码取自Express.js)

exports = module.exports = createApplication;

我以前见过类似的模式,那里有这种类型的引用变量链,例如:

x = y = z

我理解出口和模块。但是看看上面的模式,我不禁要问它到底是如何工作的。

我按照一般的经验法则去做。Exports '是真正的交易,而' Exports '是它的助手,更多信息在这里

模块模式是这样的吗(不改变module.exports)?

exports = module.exports = {};

,

exports.name = 'hello' 

结果
exports = module.exports = {name: 'hello'}

当您更改导出的引用时会发生什么?

exports = {name: 'bob'}

现在当你添加到exports时,它将引用' {name: 'bob'},并且不再与module.exports有任何关系。

你的直觉是正确的。我将从下到上:

Node.js包装器

在运行任何文件之前,Node.js将整个脚本封装在立即调用的函数表达式(IIFE)中:

(function (exports, require, module, __filename, __dirname) {
    // ...script goes here...
});

这就是它如何将moduleexports变量引入作用域;它们只不过是函数的参数而已。

使用exports

关于module.exportsexports别名的Node.js文档非常有帮助。首先,module.exportsexports变量都指向由模块系统创建的同一个空对象。

如果一个模块只需要导出一个普通的旧JavaScript对象和一些属性设置,exports是所有需要的:

exports.get = function(key) {
    // ...
};
exports.set = function(key, value) {
    // ...
};

当代码require()使用此模块时,结果将看起来像:

{
    get: [Function],
    set: [Function]
}

替换module.exports

但是,Express导出一个构造函数createApplication作为根值。要导出函数本身,而不是将其赋值给导出对象的属性,它必须首先完全替换导出对象:

module.exports = createApplication;

现在,exports没有更新,仍然引用旧对象,而module.exports是对createApplication的引用。但是如果继续阅读,您会注意到除了构造函数之外,Express还导出了其他几个属性。虽然将这些属性赋给module.exports的新值就足够了,但将exports重新赋值,使其再次成为module.exports的别名,然后将这些属性赋给exports,这相当于在module.exports上赋值。

因此,这些例子在功能上是等价的:
module.exports = createApplication;
function createApplication() {
    // ...
}
module.exports.application = proto;
module.exports.request = req;
module.exports.response = res;

但是下面这个更简洁:

exports = module.exports = createApplication;
function createApplication() {
    // ...
}
exports.application = proto;
exports.request = req;
exports.response = res;

无论哪种方式,结果都是相同的,在根目录下有一个名为createApplication的函数,其属性可用:

{
    [Function: createApplication]
    application: [Object],
    request: [Object],
    response: [Object],
    // ...a few other properties...
}