require.js项目中的使用
1.主要用于管理js文件,按需加载js。
使用:
//在HTML中只需引入
<script src="lib/requirejs/require.js" data-main="js/main"></script>
// 此时main.js为js入口文件,主要解析main.js。 这里main.js名字不是规定死的。
main.js文件:
require.config({
//baseUrl: "../lib",
shim: { // 导入不符合(不兼容)AMD CMD规范的库,或文件
'bootstrap': {
deps: ['jquery'], //加载 bootstrap需要依赖的文件
exports: 'bootstrap' //导出名为 bootstrap
}
},
paths: { //导入符合 AMD CMD规范的库或文件
/*"jquery": [
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min',
'../lib/jquery/dist/jquery.min'
],*/
"jquery": "../lib/jquery/dist/jquery.min",
"bootstrap": "../lib/bootstrap/dist/js/bootstrap.min",
"index":"index",
"getJson":"getJson"
}
});
require(['jquery','bootstrap','index','getJson'], function ($,bootstrap,index,getJson){
//这里的$ bootstrap 等参数只是相应库的引用别名,例如我需要调用index.js文件内的一个方
法,只需要 index.obj.相应的方法即可调用。其他同理
//$(".p1").text("hello world");
console.log(index.web.add(11));
let getList = ()=> {
var str ="";
console.log(getJson);
getJson.getJSON("http://localhost:3000/info",'get')
.then(function(req) {
console.log(req);
if(req.code =='200'){
var data = req.result;
for(let i=0;i<data.length;i++){
str+=`<li><span>作者:</span>${data[i].name}<span>内容:</span>${data[i].content}</li>`
};
$(".messageList ul").html(str);
}
}, function(error) {
console.error('出错了', error);
});
};
getList();
//主程序代码编写区
});
其他js文件的写法:(AMD与CMD规范写法)
//CMD规范写法 依赖就近写法 哪里需要使用其他文件内的方法,或属性值,
//直接在回调函数中, var demo=require('demo')
define(function (require, exports, module){ // require.js的模块,组件,面向对象式开发
//require 用于导入 此文件所需要的依赖文件
//exports 用于导出
//module同上
var doSomething = function() {
return 10;
};
/*代码编写区*/
//导出
/*导出写法1 (优先级最高)*/
return {
doSomething:doSomething
};
/*导出写法2*/
module.exports={
doSomething:doSomething
}
/*导出写法3*/
exports.doSomething=donSomething;
});
//AMD规范写法 : 依赖前置写法
//依赖事先引入
define(['demo'],function(){
/*其他写法同上*/
})