简体   繁体   English

打包需要jQuery的JavaScript库的最佳方法是什么?

[英]Best way to package a JavaScript library that requires jQuery?

I am writing a very basic JavaScript library that uses the $.ajax() function of jQuery. 我正在编写一个非常基本的JavaScript库,它使用jQuery的$ .ajax()函数。

How should I manage this dependency? 我该如何管理这种依赖? Should I instruct users of my library to include jQuery themselves? 我应该指示我的库的用户自己包含jQuery吗? Should I use something like RequireJS or script tag insertion to load jQuery within the library? 我应该使用诸如RequireJS或脚本标记插入之类的东西来加载库中的jQuery吗? If the latter would be better, how do I do this without causing a conflict if the user is already using jQuery? 如果后者会更好,如果用户已经在使用jQuery,如何在不引起冲突的情况下执行此操作?

I think it kinda depends if you have more dependencies, other than jQuery. 我认为这取决于你是否有更多的依赖,而不是jQuery。

If jQuery is your only dependency, and your library doesn't really need it's own module dependency system, I wouldn't recommend RequireJS. 如果jQuery是你唯一的依赖项,并且你的库并不真正需要它自己的模块依赖系统,我不会推荐RequireJS。 Just check for the existence of jQuery in your library, and throw an error otherwise. 只需检查库中是否存在jQuery,否则会抛出错误。

If you're however looking to make an flexible and maintainable libary, I would recommand using some module loader (like RequireJS). 如果您正在寻找一个灵活且可维护的库,我建议使用一些模块加载器(如RequireJS)。 This also gives you the advantage of using a build system which allows you to combine and pack your library 这也为您提供了使用构建系统的优势,该系统允许您组合和打包库

I ended up writing my own function to fetch JSON data as silly little me recommended in the original post. 我最后编写了自己的函数来获取JSON数据,就像在原帖中推荐的那么愚蠢 Thanks to everyone who replied. 感谢所有回复的人。 The guidance on JavaScript library dependencies was very valuable, even though I went down this other route. 关于JavaScript库依赖关系的指导是非常有价值的,即使我走了另一条路线。

I used this Stack Overflow answer as a guide for writing my own function to fetch JSON. 我使用这个Stack Overflow答案作为编写我自己的函数来获取JSON的指南。 I needed to fetch the data synchronously, so I adjusted the function with the tips outlined in this other article . 我需要同步获取数据,因此我使用其他文章中概述的提示调整了函数。

In the end, my function looked like this. 最后,我的功能看起来像这样。 I hope it helps someone else who comes along. 我希望它可以帮助其他人。

var fetchJSON = function(path, callback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.open('GET', path, false);
  httpRequest.send();
  if (httpRequest.readyState === 4) {
    if (httpRequest.status === 200) {
      var data = JSON.parse(httpRequest.responseText);
      if (callback) callback(data);
    }
  }
}

I would recommend you to advice the users to include jquery first. 我建议你先建议用户包含jquery。 If you let me choose any example, you will see that this is a really used approach (eg .net framework) 如果你让我选择任何一个例子,你会发现这是一个真正使用的方法(例如.net框架)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM