Reference link
What is the use of requireJS?
file directory:
require
How to use requireJS?
1. Introduce requirejs and specify the main entry file:
//index.html中
<script src="./js/plug/require.js" data-main="./js/config.js"></script>
- 1
- 2
The * attribute data-main is to tell requirejs: after loading itself, immediately load the real entry file config.js, which is generally used to configure requirejs and load the real program module.
2. Configure the entry file:
//config.js中
requirejs.config({
baseUrl: './js', //js主文件夹路径
paths: { //对应所需文件路径
jquery: 'plug/jquery-3.1.0.min', //省略后缀.js
bootstrap: 'plug/bootstrap.min',
main: 'control/main',
greet: 'control/greet' //非AMD格式js
},
shim: { //引用非AMD格式js文件内的函数
// hello: { exports: 'hello' } //exports 只引用非AMD格式js文件内的一个函数
greet:{
init: function(){ //init 引用非AMD格式js文件内的多个函数
return {
name2: 'name',
sex: 'sex'
}
}
}
},
map: {
'*': {
'css': 'plug/require-css.min'
}
}
});
requirejs(['main','greet'],function(main){
main.alertCont(3);
main.add(3,5);
$('.name').text(main.name);
name('孙中山');
sex('男');
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
*exports can expose a global variable in a non-requirejs code as a reference to the module, but if I want to expose multiple global variables at the same time, I need to use init.
* When exports and init exist at the same time, exports will be ignored.
//main.js中(AMD格式js)
define(['jquery','css!../css/style.css'],function(){
return { //返回对象
alertCont : function(cont){
console.log(cont);
},
add : function(x,y){
$('.num').text(x+y);
},
name : 'lidysun',
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
//greet.js(非AMD格式js)
function name(name) {
console.log('姓名:' + name);
}
function sex(sex) {
console.log('性别:' + sex);
}
...