如何在Node.js中导出对象引用模块.导出



在Node.js中,module对象包含一个exports属性,该属性是一个空对象。此对象可用于引用module.exports(exports.a="a";(,除非已重新分配(module.exports="one";(。

我的问题是,是什么让这个导出对象引用模块.exports?

CommonJS模块实际上非常简单:您将所有代码放在一个文件中,然后将其封装在一个函数中。执行该函数,并将执行后的module.exports的值返回给调用者。

您可以在node.js源代码中看到该函数的头部:

const wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'n});'
];

包装器应用于require'd文件中的代码,然后调用如下:

const exports = this.exports;
const thisValue = exports;
const module = this;
if (requireDepth === 0) statCache = new Map();
if (inspectorWrapper) {
result = inspectorWrapper(compiledWrapper, thisValue, exports,
require, module, filename, dirname);
} else {
result = compiledWrapper.call(thisValue, exports, require, module,
filename, dirname);
}

正如您所看到的,它非常简单。const exports = this.exports,然后exports作为参数传递给包装函数-因此它们最初指向相同的值,但如果您重新分配其中一个,则它们不再指向。

最新更新