我想使用 requireJS,我正在使用 jQuery。 我不想使用 requireJS 和 jQuery 的组合版本,因为我没有使用最新的 jQuery 版本。 使用 requireJS 的最佳方式是什么?
最佳答案
这也是我的确切问题!我还必须使用旧的 jQuery,但也必须使用更“传统”的 javascript 库。最好的技术是什么? (如果您不介意,我可能会编辑您的问题以使其更广泛。)这是我学到的。
RequireJS 作者 James Burke 解释了 advantages of the combined RequireJS + jQuery file .你得到两件事。
模块
jquery
可用,它是 jQuery 对象。这是安全的:// My module depends on jQuery but what if $ was overwritten? define(["jquery"], function($) { // $ is guaranteed to be jQuery now */ })
jQuery 已在任何
require()
或define()
内容之前加载。所有模块都保证 jQuery 已准备就绪。您甚至不需要require/order.js
插件,因为 jQuery 基本上被硬编码为首先加载。
对我来说,#2 不是很有帮助。大多数实际应用程序都有 许多 .js
文件,必须以正确的顺序加载这些文件——令人遗憾但事实如此。只要您需要 Sammy 或 Underscore.js,组合的 RequireJS+jQuery 文件就无济于事。
我的解决方案是编写简单的 RequireJS 包装器,使用“order”插件加载我的传统脚本。
例子
假设我的应用程序具有这些组件(按依赖关系)。
- 我的应用程序,greatapp
- greatapp 依赖于一个自定义的jquery(我必须使用旧版本)
- greatapp 依赖于 my_sammy(SammyJS 加上我必须使用的所有插件)。这些必须按顺序
- my_sammy 依赖于 jquery(SammyJS 是一个 jQuery 插件)
- my_sammy 依赖于sammy.js
- my_sammy 依赖于sammy.json.js
- my_sammy 依赖于sammy.storage.js
- my_sammy 依赖于 sammy.mustache.js
在我看来,以上所有以 .js
结尾的都是“传统”脚本。没有 .js
的一切都是 RequireJS 插件。关键是:高层的东西(greatapp,my_sammy)是模块,在更深的层次上,它回落到传统的 .js
文件。
启动
这一切都始于 Bootstrap 告诉 RequireJS 如何启动。
<html>
<head>
<script data-main="js/boot.js" src="js/require.js"></script>
</head>
</html>
在 js/boot.js
中,我只放置了配置以及如何启动应用程序。
require( // The "paths" maps module names to actual places to fetch the file.
// I made modules with simple names (jquery, sammy) that will do the hard work.
{ paths: { jquery: "require_jquery"
, sammy : "require_sammy"
}
}
// Next is the root module to run, which depends on everything else.
, [ "greatapp" ]
// Finally, start my app in whatever way it uses.
, function(greatapp) { greatapp.start(); }
);
主要应用
在 greatapp.js
中,我有一个看起来很正常的模块。
define(["jquery", "sammy"], function($, Sammy) {
// At this point, jQuery and SammyJS are loaded successfully.
// By depending on "jquery", the "require_jquery.js" file will run; same for sammy.
// Those require_* files also pass jQuery and Sammy to here, so no more globals!
var start = function() {
$(document).ready(function() {
$("body").html("Hello world!");
})
}
return {"start":start};
}
传统文件的 RequireJS 模块包装器
require_jquery.js
:
define(["/custom/path/to/my/jquery.js?1.4.2"], function() {
// Raw jQuery does not return anything, so return it explicitly here.
return jQuery;
})
require_sammy.js
:
// These must be in order, so use the "order!" plugin.
define([ "order!jquery"
, "order!/path/to/custom/sammy/sammy-0.6.2-min.js"
, "order!/path/to/custom/sammy/plugins/sammy.json-0.6.2-min.js"
, "order!/path/to/custom/sammy/plugins/sammy.storage-0.6.2-min.js"
, "order!/path/to/custom/sammy/plugins/sammy.mustache-0.6.2-min.js"
]
, function($) {
// Raw sammy does not return anything, so return it explicitly here.
return $.sammy;
}
);
关于jquery - 如何同时使用 requireJS 和 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4535926/