javascript模块化编程03AMD模块化编程规范
规范
说明
AMD规范,全称是Asynchronous Module Definition,即异步模块加载机制。从它的规范描述页面看,AMD很短也很简单,但它却完整描述了模块的定义,依赖关系,引用关系以及加载机制。作为一个规范,只需定义其语法API,而不关心其实现。AMD规范简单到只有一个API,即define函数:
define([module-name?], [array-of-dependencies?], [module-factory-or-object]);
其中:
module-name: 模块标识,可以省略。
array-of-dependencies: 所依赖的模块,可以省略。
module-factory-or-object: 模块的实现,或者一个JavaScript对象。
从中可以看到,第一个参数和第二个参数都是可以省略的,第三个参数则是模块的具体实现本身。
简单点说模块的加载是异步的,更适用于浏览器,因为异步的天生的好处就是不会堵塞
基本语法
定义暴露模块
1.定义没有依赖的模块
define(function(){ return 模块 });
2.定义有依赖的模块
define([依赖模块1,依赖模块2,…,function(依赖模块1,依赖模块2,…){
return 模块 }])
引入使用模块
require([依赖模块1,依赖模块2,…,function(依赖模块1,依赖模块2,…){}])
语法实现
没有遵循AMD模块化规范开发的例子
所有的JS文件都要加载,有开发人员自己引入JS文件,容易出错在依赖上需要自己明确关系
项目文件结构
|NoAmd
|----js
| |----alerter.js
| |----dataService.js
|----app.js
|----index.html
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- 没有模块化规范依赖顺序自己控制,大型项目文件较多容易出错 -->
<script src="./js/dataService.js"></script>
<script src="./js/alerter.js"></script>
<script src="./app.js"></script>
</head>
<body>
</body>
</html>
dataServices.js代码
//定义一个没有依赖的模块
(function(window){
let name = 'dataServices.js';
function getName(){
return name;
}
window.dataService = {getName};
})(window);
alerter.sj代码
//定义一个有依赖的模块
(function(window,dataService){
let msg = 'alerter.js';
function showMsg(){
console.log(msg,dataService.getName());
}
window.alerter = {showMsg};
})(window,dataService);
遵循AMD规范的例子
项目结构
|RequireJS
|----js
| |----lib
| |----module
| | |----dataServices.js
| | |----alerter.js
| |----main.js
|----index.html
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/require.js/2.3.5/require.js" data-main="js/main.js"></script>
</head>
<body>
</body>
</html>
dataServices.js
//定义没有依赖的模块使用REQUIREJS语法
define(function(){
let name = "dataServices.js";
function getName(){
return name;
}
//暴露模块
return {getName};
})
alerter.js
// 定义有依赖的模块
define(['dataServices','jquery'],function(dataServices,$){
let msg = "alerter.js";
$('body').css("background",'#000');
function showMsg(){
console.log(msg,dataServices.getName());
}
//暴露模块
return {showMsg};
})
main.js
//主文件
(function(){
requirejs.config({
baseUrl: './js/', //基本路径,以当前文件所在路径作为判断依据
paths:{//配置路径
dataServices: 'module/dataServices',
alerter: 'module/alerter',
jquery: 'https://cdn.bootcss.com/jquery/2.0.1/jquery',//jquery本身就支持AMD规范,在其内部就已经定义了jquery
angular: 'https://cdn.bootcss.com/angular.js/1.7.0/angular.min'
},
shim:{
angular:{
exports: 'angular'
}
}
})
requirejs(['alerter','angular'],function(alerter,angular){
console.log(angular);
alerter.showMsg();
})
})()