我现在一直在使用RequireJS,但我仍然在努力掌握它...
我有一个包含许多JS插件的简单项目,根据我的理解,我通过paths
对象提取这些插件,但有时,当我添加一个新插件并运行时我的脚本,我得到一个控制台错误,解释依赖是undefined
。
这是我的JS:
require.config({
"paths": {
"jquery": "/content/themes/my-theme/bower_components/jquery/dist/jquery.min",
"foundation": "/content/themes/my-theme/bower_components/foundation/js/foundation.min",
"slick": "/content/themes/my-theme/bower_components/slick.js/slick/slick.min",
"scrollmagic": "/content/themes/my-theme/bower_components/scrollmagic/scrollmagic/minified/ScrollMagic.min"
},
"shim": {
"foundation": ["jquery"],
"slick": ["jquery"]
}
});
require(['jquery', "foundation", "slick", "scrollmagic"], function($) {
/* --------------------
Variables
---------------------*/
var
bodyEl = $( 'body' ),
isOpen = false,
content = $( '.content' ),
openbtn = $( '#open-button' ),
closebtn = $( '#close-button' ),
controller = new ScrollMagic.Controller();
$(document).foundation();
$(document).ready(function() {
navInit();
$('.main-slider').slick({
dots: false,
arrows: false,
infinite: true,
speed: 300,
slidesToShow: 1,
autoplay: true,
autoplaySpeed: 4000
});
});
});
我的项目运行正常,直到我添加了最新的依赖项scrollMagic
...在浏览器中运行时出现以下错误:Uncaught TypeError: Cannot read property 'Controller' of undefined
我考虑将此添加到shim
,但由于插件并非特定依赖于任何(尚未),因此应该是必要的。
我在这里做错了什么?
答案 0 :(得分:1)
就像你为jQuery添加$一样,你需要为传入的其他模块添加参数
require(['jquery', "foundation", "slick", "scrollmagic"], function($, foundation, slick, ScrollMagic) {
这将假设这些是AMD兼容模块。
如果没有,您需要填充它们并添加一个导出,将库变量分配给exports属性。以下是http://requirejs.org/docs/api.html
的示例shim: {
'backbone': {
//Once loaded, use the global 'Backbone' as the
//module value.
exports: 'Backbone'
},