具体的理论就不讲了,可以参考
http://www.ruanyifeng.com/blog/2012/10/javascript_module.html
http://www.ruanyifeng.com/blog/2012/10/asynchronous_module_definition.html
http://www.ruanyifeng.com/blog/2012/11/require_js.html
直接上demo
首先创建文件,其中define的是采取amd格式定义的
1
2
3
4
5
6
7
8
9
|
// add.js define( function (){ var add = function (x,y){ return x+y; }; return { add: add }; }); |
1
2
3
4
5
6
7
8
9
|
// multiply.js define( function (){ var multiply = function (x,y){ return x*y; }; return { multiply: multiply }; }); |
1
2
3
4
5
6
7
8
9
10
11
|
// divide.js define( function (){ var divide= function (a,b){ return a/b; }; return { divide:divide }; }) |
1
2
3
4
5
|
// noAMD.js function testm(a,b){ return a-b; } window.test=test2; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
//main.js require.config({ baseUrl:"js", paths: { "js1" : "add" , "js2" : "divide" , "js4" : "noAMD" }, shim:{ "test" :{ exports: "js4" } } }); require([ "js1" , "js2" , "js/multiply" , 'js4' ], function (j1,j2,j3,j4){ var a=21,b=3; alert(j1.add(a,b)); alert(j2.multiply(a,b)); alert(j3.divide(a,b)); alert(testm(a,b)) }) |
1
2
3
4
5
6
7
8
9
10
|
< html > < head > < meta name="generator" content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" /> < title ></ title > < script src="require.js" data-main="main" defer async="true"> </ script > </ head > < body ></ body > </ html > |
此处需要注意非amd格式编写的,需要使用shim
文件:r9.zip