"出口"的目的是什么?在垫片下面的财产?真的需要吗?
requirejs.config({
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
我问因为它似乎是多余的 - 当模块包含在依赖列表中时,我们将再次指定导出的名称作为函数参数:
define(['backbone'], function (Backbone) {
return Backbone.Model.extend({});
});
答案 0 :(得分:35)
如果您的示例中未使用shim
,那么您作为参数传递的Backbone
对象将是未定义的,因为Backbone不符合AMD标准,并且不会返回RequireJS要使用的对象。
define(['backbone'], function (Backbone) {
// No shim? Then Backbone here is undefined as it may
// load out of order and you'll get an error when
// trying to use Model
return Backbone.Model.extend({});
});
为了给出一些上下文,我将使用r.js优化器吐出的代码,但我会为此示例简化它。通过阅读优化器产生的内容,它帮助我理解了它的重点。
匀化的Backbone会有点像这样:
// Create self invoked function with the global 'this'
// passed in. Here it would be window
define("backbone", (function (global) {
// When user requires the 'backbone' module
// as a dependency, simply return them window.Backbone
// so that properites can be accessed
return function () {
return global.Backbone;
};
}(this)));
关键是当你要求一个模块时,给RequireJS一些东西返回给你,它会确保在这之前先加载。对于优化器,它只是简单地嵌入库。
答案 1 :(得分:29)
如果您不使用“export” Backbone ,那么您无法将模块中的语言环境引用获取到Backbone(window.Backbone)中定义的Backbone.js的。
//without export Backbone
shim : {
'bbn':{
//exports:'Backbone',
deps:['underscore']
},
'underscore': {
exports: '_'
}
};
require(['bbn'], function(localBackbone) {
//localBackbone undefined.
console.log('localBackbone:,' localBackbone);
});
RequireJs解释如下:
//RequireJS will use the shim config to properly load 'backbone' and give a local
//reference to this module. The global Backbone will still exist on
//the page too.
define(['backbone'], function (Backbone) {
return Backbone.Model.extend({});
});
RequireJS将使用shim config获取全局Backbone
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
答案 2 :(得分:2)
另请注意,您可能希望在“exports”中使用插件的实际导出。例如,
requirejs.config({
shim: {
'jquery.colorize': {
deps: ['jquery'],
exports: 'jQuery.fn.colorize'
},
'jquery.scroll': {
deps: ['jquery'],
exports: 'jQuery.fn.scroll'
},
'backbone.layoutmanager': {
deps: ['backbone']
exports: 'Backbone.LayoutManager'
},
"jqueryui": {
deps: ["jquery"],
//This is because jQueryUI plugin exports many things, we would just
//have reference to main jQuery object. RequireJS will make sure to
//have loaded jqueryui script.
exports: "jQuery"
},
"jstree": {
deps: ["jquery", "jqueryui", "jquery.hotkeys", "jquery.cookie"],
exports: "jQuery.fn.jstree"
},
"jquery.hotkeys": {
deps: ["jquery"],
exports: "jQuery" //This plugins don't export object in jQuery.fn
},
"jquery.cookie": {
deps: ["jquery"],
exports: "jQuery" //This plugins don't export object in jQuery.fn
}
}
});
更多:https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0#wiki-shim
答案 3 :(得分:1)
Shim导出是为了让requirejs知道如何处理非AMD模块。没有它,在模块启动时,仍会加载定义块中的依赖项。它表示requirejs已停止加载资源,模块可以开始使用它。
至少,这就是我的看法。