如何使用 Node.js 在服务器端管理多个 JS 文件
我正在使用 Node.js 开发一个项目,服务器端代码变得足够大,我想将其拆分为多个文件。看来这已经在客户端完成了很长时间,开发是通过为每个文件插入一个 script
标签来完成的,并且只有用于分发的东西才像“Make”一样用于将所有内容放在一起。我意识到连接所有服务器端代码是没有意义的,所以我不会问如何做到这一点。我能找到的最接近的东西是 require()
,但是它的行为与 script
在浏览器中的行为不太一样,因为需要的文件不共享公共命名空间。
看看一些较旧的 Node.js 项目,例如 Shooter,看起来是这样曾经不是这样的,或者我在代码中遗漏了一些非常简单的东西。我所需的文件无法在编译时或运行时访问全局调用命名空间。是否有任何简单的方法可以解决这个问题,或者我们是否被迫使所有必需的 JS 文件完全独立于调用范围?
I'm working on a project with Node.js and the server-side code is becoming large enough that I would like to split it off into multiple files. It appears this has been done client-side for ages, development is done by inserting a script
tag for each file and only for distribution is something like "Make" used to put everything together. I realize there's no point in concatting all the server-side code so I'm not asking how to do that. The closest thing I can find to use is require()
, however it doesn't behave quite like script
does in the browser in that require'd files do not share a common namespace.
Looking at some older Node.js projects, like Shooter, it appears this was once not the case, that or I'm missing something really simple in my code. My require'd files cannot access the global calling namespace at compile time nor run time. Is there any simple way around this or are we forced to make all our require'd JS files completely autonomous from the calling scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要公共名称空间,因为全局变量是邪恶的。在节点中,我们定义模块
您定义一个模块,然后通过写入
exports
来为您的模块公开公共 API。处理这个问题的最佳方法是依赖注入。您的模块公开一个
init
函数,并将依赖项的对象哈希传递到您的模块中。如果您确实坚持访问全局范围,那么您可以通过
global
访问它。每个文件都可以写入和读取global
对象。同样,您不想使用全局变量。You do not want a common namespace because globals are evil. In node we define modules
You define a module and then expose a public API for your module by writing to
exports
.The best way to handle this is dependency injection. Your module exposes an
init
function and you pass an object hash of dependencies into your module.If you really insist on accessing global scope then you can access that through
global
. Every file can write and read to theglobal
object. Again you do not want to use globals.回复 @Raynos 答案,如果模块文件位于包含它的文件旁边,则应该是
如果模块是通过 npm 发布并安装的,或者显式放入
./node_modules/
文件夹中,那么是正确的。
re @Raynos answer, if the module file is next to the file that includes it, it should be
If the module is published on, and installed through, npm, or explicitly put into the
./node_modules/
folder, then theis correct.