AMD_RequireJS
时间:2020-08-11 15:49:21
收藏:0
阅读:65
模块化第二种规范----AMD
说明
专门用于浏览器端,模块的加载时异步的
基本语法
定义暴露模块
//定义没有依赖的模块
define(functioin(){
return 模块
})
//定义有依赖的模块
define([‘module1‘,‘module2‘],function(){
return 模块
})
引入使用模块
require([‘module1‘,‘module2‘],function(m1,m2){
使用m1/m2
})
实现(浏览器端)
Require.js
示 例
1、noAMD普通模式
项目目录
dataService.js
// 定义一个没有依赖的模块
(function(window){
let name = "dataService.js"
function getName(){
return name
}
window.dataService = {getName}
})(window)
alerter.js
// 定义一个有依赖的模块
(function(window,dataService){
let msg = "alerter.js"
function showMsg(){
console.log(msg,dataService.getName())
}
window.alerter = {showMsg}
})(window,dataService)
app.js
(function(alerter){
alerter.showMsg()
})(alerter)
test1.html
<script src="./app.js"></script>
运行页面发现报错
最后结果
2、require.js 使用----自定义模块
1、下载require.js 并引用
官网:http://www.require.cn/
github: https://github.com/require/require.js
2、创建项目结构
3、定义require.js 的模块代码
require.js官网下载
dataService.js模块
define(function(){ let name = "dataService.js" function getName(){ return name } // 暴露模块 return {getName} })
alerter.js
// 定义一个有依赖的模块 define([‘dataService‘],function(dataService){ let msg = ‘alerter.js‘ function showMsg(){ console.log(msg,dataService.getName()) } // 暴露模块 return {showMsg} })
main.js
dataService: ‘./modules/dataService.js‘ 注意不能加js
(function(){ requirejs.config({ baseUrl: ‘js/‘,//基本的路径 paths: {//配置路径 相当于导入模块 dataService: ‘./modules/dataService‘, alerter:‘./modules/alerter‘ } }); requirejs([‘alerter‘],function(alerter){ alerter.showMsg() }) })()
官网中的方法配置说明
index.html
- 防止js加载阻塞页面渲染(异步)
- 使用程序调用的方式加载js,防出现如下丑陋的场景
- 不用关心相互依赖的顺序
<!-- 引入require.js 并指定js主文件的入口 --> <script data-main="js/main.js" src="js/libs/require.js"></script>
3、AMD规范--使用第三方模块
评论(0)