我正在使用RequireJS 2.0.1 进行一些实验。我的目标是正确加载jQuery,Underscore和Backbone。从原始的RequireJS doc中,我发现作者J. Burke添加了(到此新版本中)new config option called shim。
然后我在这里写下了这些东西:index.html
<!DOCTYPE html>
<html>
<head>
<title>Testing time</title>
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>Testing time</h1>
</body>
</html>
scripts/main.js
requirejs.config({
shim: {
'libs/jquery': {
exports: '$'
},
'libs/underscore': {
exports: '_'
},
'libs/backbone': {
deps: ['libs/underscore', 'libs/jquery'],
exports: 'Backbone'
}
}
});
define(
['libs/jquery', 'libs/underscore', 'libs/backbone'],
function (jQueryLocal, underscoreLocal, backboneLocal) {
console.log('local', jQueryLocal);
console.log('local', underscoreLocal);
console.log('local', backboneLocal);
console.log('global', $);
console.log('global', _);
console.log('global', Backbone);
}
);
一切似乎都可以正常工作,但是我有一种缺失的感觉,我知道有AMDed版本的jQuery和Underscore,但是如果安装是如此简单,我不明白为什么要使用它们。
那么,此设置正确吗?或者我缺少什么?
最佳答案
如果库尚未调用define()
声明模块,则只需使用“shim”配置。 jQuery已经做到了这一点,因此您可以将其从垫片配置中删除。上面的代码将按原样运行,但是jQuery的导出填充程序配置将被忽略,因为jQuery将在完成填充程序之前调用define()
。
填充程序与使用脚本调用define()
定义模块的缺点:
define()
时可以实现。如果您为最终部署进行构建/优化并将所有脚本组合为一个脚本,那么这并不是真正的缺点。 关于javascript - 使用RequireJS 2.0.1和shim加载jQuery,Underscore和Backbone,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10866740/