javascript - 如果我在 `module.exports` 上定义模块,那么 `global` 有什么好处?

标签 javascript node.js

我最近在学习 Node 导入系统。

我知道如何使用 Node 的 module.exports:

// file_1
var MyClass = module.exports = {}
// file_2
var MyClass = require("./file_1.js")

以及我如何使用全局变量

// file_1
global.MyClass = {foo: "bar"}
// file_2
require("./file_1.js")
console.log(MyClass.foo)

我个人更喜欢全局方法,但有人告诉我,在我的文件中导出类也是一种很好的做法。

问题是,我的主文件现在实际上没有任何自己的类。所有类都位于所需的文件中,并且应用程序的所有组件都存在于 global 对象中。

我不太确定在我的主文件上使用 module.exports 是否有好处。我认为一个简单的方法就是简单地导出整个全局对象。不过,由于这个对象可能有点大,我担心我不确定是否有用的功能会导致性能下降。

如果我在 global 对象上定义模块,那么使用 module.exports 有什么意义吗?

最佳答案

I prefer the globals approach personally, but I've been told that it's good practice to also export a class in my files.

我确信您已经被告知,使用全局变量是一种不好的做法,您应该通过module.exports导出您的类/em>。不另外。

I'm not really sure there's a benefit to using module.exports on my main file.

不,您的主文件(通常作为脚本而不是模块执行)不需要导出任何内容。把它放在一边吧。使用局部变量,或者如果必须的话创建一​​些全局变量。

关于javascript - 如果我在 `module.exports` 上定义模块,那么 `global` 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600013/

相关文章:

javascript - 标记错误

javascript - 使用 Javascript 进行 HtmlEditorExtender 的 Google 翻译不起作用

javascript - 在 3000 端口上使用 https 的 Node.js socket.io

javascript - 如何将 jSTL/JSP 变量转换为 javascript 变量?

Javascript获取数字的前两位数字

node.js - 如何在 MongoDB 的数组中提取项目的一个实例?

javascript - Node require() 存在两个互相需要的脚本的问题

node.js - 如何停止在 forEach 中附加字符串?

MySQL 8/Node 连接器 API : Table is undefined

javascript - DerbyJS - 无法让 Mongo 存储工作