0

在 Node.js 中,模块对象包含一个导出属性,即一个空对象。此对象可用于引用 module.exports (exports.a = "A"; ),除非它被重新分配 ( module.exports = "one"; )。

我的问题是 - 是什么让这个导出对象引用 module.exports?

4

1 回答 1

0

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作为参数传递给包装函数 - 因此它们最初指向相同的值,但如果您重新分配其中任何一个,则它们不再这样做。

于 2020-03-31T18:04:54.240 回答