#RequireJS 使用笔记
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
Only works with AMD modules
Folder structure:
index.html
- assets
- js
+ lib
jquery.js
modernizr.js
underscore.js
my_module.js //modules
- page
home.js //home page
another_page.js
common.js //config, linked via data-main
##使用config index.html:
<script data-main="assets/js/common" src="assets/js/lib/require.js"></script>
<script>
//inline script, load home.js when opening the home page
require(['common'],function() {
//once common has loaded, load up this page
require(['page/home']); //relative to the base url
});
</script>
common.js:
require.config({
baseUrl: "assets/js",
//relative to the root location of the site
paths: {
jquery: [
"location", //eg. CDN url
//once location fails, load this
"backup location" //eg. local url,
//relative to the base url, e.g. "lib/jquery"
],
modernizr: [...]
}
});
home.js
//this page requires the jquery module
//names of the module are from the config list
//parameters of the callback function correspond to the modules
define(['jquery','underscore'],function($,_){
//code
})
##不使用config: index.html
<script>
require(['assets/js/lib/my_module'],function(Y){
//code
});
</script>
my_module.js
//不使用config指向jquery-[版本号]时,需要将jquery文件重命名为jquery.js
define(['jquery'],function($){//my_module与jquery在同级目录
//code
return Methods;
});
注意:
- 用于js文件(包括data-main指向的主模块home.js或my_app.js,以及自定义模块my_module.js)
- require用于调用代码块(如index.html中的)
注意: jQuery defines itself as 'jquery' when it detects AMD/requireJS. Do not re-define it using other names.
注意: 正确填写绝对路径或相对路径
注意: 将多个自定义模块写在同一个js文件内, 需要使用optimizer
##相互依赖的library 因为AMD模块是异步加载,有依赖的插件需要设置shim
shim: Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.
###例子:backbone.js依赖jquery和underscore.js
requirejs.config({
shim: {
'backbone': {
//dependencies
deps: ['underscore', 'jquery'],
exports: Backbone
},
'underscore': {
exports: '_'
}
}
});
使用Backbone
define(['backbone'], function (Backbone) {
return Backbone.Model.extend({});
});
###例子:jquery插件
requirejs.config({
baseUrl: 'js',
paths: {
'jquery': 'lib/jquery',
'jquery.uriAnchor': 'lib/jquery.uriAnchor'
}
shim:{
'jquery.uriAnchor': {
deps: ['jquery'],
exports: '$.uriAnchor'
}
}
});
For "modules" that are just jQuery or Backbone plugins that do not need to export any module value, the shim config can just be an array of dependencies:
shim:{
'jquery.uriAnchor': ['jquery']
}
二者效果一样。 例使用:$.uriAnchor
define(['jquery',‘jquery.uriAnchor’],function($, uriAnchor) {
$.uriAnchor.setAnchor({
menu: (stateMap.isMenuRt ? 'open' : 'closed')
});
});