我最近在学习 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/