将代码与依赖项合并?
这可能很简单,但我必须说我对这个话题有点困惑。
我正在基于两个流行的库编写代码:
- jQuery
- underscore.js
我只是想知道隔离代码和防止冲突的最佳方法是什么以及如何将其与其依赖项合并?
我的意思是把它们放在同一个文件中。
This might be quite simple, but I must say I'm a bit confused on this topic.
I'm writing code based on two popular libraries:
- jQuery
- underscore.js
I am just wondering what would be the best way to isolate the code and prevent conflicts and how to merge it with its dependencies?
By merging I mean putting them within the same file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以轻松地将它们两个放在同一个文件中,因为它们唯一变为全局的东西是
window._
、window.$
和window.jQuery< /代码>。其他变量和函数都包装在本地作用域中,因此不会发生冲突。
编辑:您自己的代码也可以放入同一文件中。如果您希望删除全局变量,jQuery 和 Underscore 都有一个无冲突方法,该方法将全局变量替换为其旧值(通常是
未定义
)。您可以将代码包装在您自己的本地范围内,这样就不再有问题了:这看起来很棘手,但让我快速解释一下。您可以在定义函数后立即执行该函数,如下所示:
您可以在其中传递参数:
$.noConflict()
和_.noConflict()
都删除全局变量变量并返回对 jQuery 和 Underscore 变量的引用。因此,您可以将这些作为参数传递到自执行函数中,每个人都很高兴(:You could easily place the two of them in the same file, because the only things they turn global are
window._
,window.$
andwindow.jQuery
. The other variables and functions are wrapped in a local scope, so there will be no conflict.Edit: Your own code could be put in the same file too. And if you prefer to remove the globals, both jQuery and Underscore have a no-conflict method, which replaces the globals with their old values (often
undefined
). You could wrap your code in your own local scope and there'll be no problems anymore:This looks quite tricky, but let me explain it very quickly. You can execute a function immediatly after defining it, like this:
And you can pass arguments in it:
Both
$.noConflict()
and_.noConflict()
remove the global variables and return a reference to the jQuery and Underscore variable. So you can pass these in the self-executing function as arguments and everybody's happy (: