javascript - CommonJs模块系统中 "module.exports"和 "exports"之间的区别

标签 javascript node.js commonjs

在此页面 ( http://docs.nodejitsu.com/articles/getting-started/what-is-require ) 上,它指出“如果要将导出对象设置为函数或新对象,则必须使用 module.exports 对象。”

我的问题是为什么。

// right
module.exports = function () {
  console.log("hello world")
}
// wrong
exports = function () {
  console.log("hello world")
}

我通过 console.logged 结果 (result=require(example.js)),第一个是 [Function],第二个是 {}

您能解释一下背后的原因吗?我在这里读了这篇文章:module.exports vs exports in Node.js 。它很有帮助,但没有解释为什么这样设计。直接返回exports的引用会有问题吗?

最佳答案

module 是一个带有 exports 属性的纯 JavaScript 对象。 exports 是一个纯 JavaScript 变量,恰好设置为 module.exports。 在文件末尾,node.js 基本上会将 module.exports“返回”到 require 函数。在 Node 中查看 JS 文件的简化方法可能是这样的:

var module = { exports: {} };
var exports = module.exports;

// your code

return module.exports;

如果您在 exports 上设置属性,例如 exports.a = 9;,也会设置 module.exports.a,因为对象在 JavaScript 中作为引用传递,这意味着如果您为同一个对象设置多个变量,它们都是同一个对象;所以 exportsmodule.exports 是同一个对象。
但是,如果您将 exports 设置为新的内容,它将不再设置为 module.exports,因此 exportsmodule.exports 不再是同一个对象。

关于javascript - CommonJs模块系统中 "module.exports"和 "exports"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59347603/

相关文章:

javascript - 如何从 FormData 检索信息

javascript - 找不到强大的命令

javascript - Node JS进程内存不足

node.js - 使用 Jenkins 运行 Grunt.js

javascript - 为什么 Javascript promise 会乱序解决?

javascript - 使用 webpack-dev-server 找不到模块 'webpack'

javascript - Mongoose ODM : Can't save encoded password because of async

javascript - 如何查找错误 : Cannot find module 的原因

css - ExtractTextWebpackPlugin 始终输出文件,即使没有更改

javascript - browserify 可以要求在 gulp 中生成乙烯基文件吗?