在 Node.js 中,模块对象包含一个导出属性,即一个空对象。此对象可用于引用 module.exports (exports.a = "A"; ),除非它被重新分配 ( module.exports = "one"; )。
我的问题是 - 是什么让这个导出对象引用 module.exports?
在 Node.js 中,模块对象包含一个导出属性,即一个空对象。此对象可用于引用 module.exports (exports.a = "A"; ),除非它被重新分配 ( module.exports = "one"; )。
我的问题是 - 是什么让这个导出对象引用 module.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
作为参数传递给包装函数 - 因此它们最初指向相同的值,但如果您重新分配其中任何一个,则它们不再这样做。