require.js

2 篇文章 0 订阅

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(){
    /*其他写法同上*/

})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值