我现在开始使用 RequireJS,并且我已经能够添加我的项目依赖项,但我仍然无法添加 jQuery 匿名函数。
例如,使用我的normal_file.js,我会执行以下操作:
normal_file.js:
define(['dependency1'], function(Dependency) {
var Test1 = ...;
return Test1;
});
Bu来自一个没有模块的文件,如下例所示,我不知道如何封装它:
lib_file.js:
(function ($) {
// Do stuff...
})(window.jQuery);
lib_file 不是我制作的,我不确定它是如何工作的,但我猜它是一个匿名自动执行函数,是这样吗?
无论如何,我的目标是在我的主代码中使用这两个文件,如下所示:
main.js:
requirejs.config({
baseUrl:'/static/editorial/js/',
paths: {
jquery: 'third_party/jquery-1.10.2',
react: 'third_party/react-with-addons'
}
});
var dependencies = [
'third_party/react-with-addons',
'third_party/jquery-1.10.2',
'build/utils/normal_file,
'third_party/lib_file
];
require(dependencies, function(React, $, Test1, ??) {
// do my stuff
});
我应该如何封装该匿名函数才能将其作为依赖项添加到我的主文件中?
最佳答案
来自 RequireJS 文档:
Ideally the scripts you load will be modules that are defined by calling define(). However, you may need to use some traditional/legacy "browser globals" scripts that do not express their dependencies via define(). For those, you can use the shim config. To properly express their dependencies.
阅读此内容:http://requirejs.org/docs/api.html#config-shim
它对您必须做什么有一个很好的解释,并给出了一个很好的例子。
基本上,您只需要为 lib_file.js
设置一个 shim 配置,这样 Require 就知道在允许您访问该脚本之前加载正确的依赖项。
关于javascript - 如何将匿名函数包含到 RequireJS 依赖项中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24048627/