在 NodeJS 中需要多个模块的最佳方法
我不太喜欢要求模块的标准方法,它是这样的:
connect = require 'connect'
express = require 'express'
redis = require 'redis'
sys = require 'sys'
coffee = require 'coffee-script'
fs = require 'fs'
它并不完全是 DRY。在一个普通的 CoffeeScript 服务器中,require dance 占据了整个脚本的相当大的一部分!我一直在玩弄以下替代方案:
"connect,express,redis,sys,coffee-script,fs"
.split(',').forEach (lib) -> global[lib] = require lib
因为我还没有看到人们尝试重构标准方法,我想我会问这样做是否合理,如果是,是否有更好的方法来做到这一点?
I don't much like the standard way to require modules, which goes something like this:
connect = require 'connect'
express = require 'express'
redis = require 'redis'
sys = require 'sys'
coffee = require 'coffee-script'
fs = require 'fs'
It's not exactly DRY. In a modest CoffeeScript server, the require dance takes up a fair chunk of the entire script! I've been toying with the following alternative:
"connect,express,redis,sys,coffee-script,fs"
.split(',').forEach (lib) -> global[lib] = require lib
Since I haven't seen people try to refactor the standard approach, I thought I'd ask if it seems reasonable to do so, and if so, are there any better ways to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,
coffee-script
不是有效的标识符,因此您的代码并未真正正确导入它。您可以使用 CoffeeScript 灵活的对象文字来很好地处理这个问题。我还会使用?=
来避免不必要的重新导入模块。基于 user211399 的答案:由于我允许您在不同的模块中使用不同的标识符导入,因此使用全局命名空间感觉特别不安全。我会在本地导入它们,如下所示。请注意,因为这使用了
eval
,所以如果您指定非法标识符,它可能不会正常失败。Note that
coffee-script
isn't a valid identifier, so your code isn't really importing it properly. You can use CoffeeScript's flexible object literals to handle this pretty nicely. I'd also use?=
to avoid unnecessarily re-importing modules. Building off of user211399's answer:Since I'm allowing you to import with different identifiers in different modules, using the global namespace feels particularly unsafe. I'd import them locally instead, as shown below. Be aware that because this uses
eval
it might not fail gracefully if you specify an illegal identifier.前一段时间我曾考虑过这个想法,结果是这样的:
最终抓破了它,然后按照通常的方式去做——这最终会带来更大的麻烦。很多时候您需要获取模块的属性或使用不同的命名方案。此外,分配给全局范围与“正常”
require
不同。对齐作业使其更易于阅读:您只需执行一次,抽象它只是不必要的复杂性。
I toyed with the idea some time ago, and ended up with this:
Ended up scratching it and just doing it the usual way - it ends up being a bigger hassle. There are plenty of times where you need to grab a module's property or use a different naming scheme. Also, assigning to global scope is not the same as a "normal"
require
. Aligning assignments makes it easier to read:You're only doing this once, abstracting it is just unnecessary complexity.