requireJS使用入门

参考链接 
requireJS有什么用? 
文件目录: 
require


requireJS怎么用? 
1.引入requirejs并指定主入口文件:

//index.html中
<script src="./js/plug/require.js" data-main="./js/config.js"></script>
  • 1
  • 2

*属性 data-main 是告诉requirejs:加载完自己后,马上去加载真正的入口文件config.js,它一般用来对requirejs进行配置,并且载入真正的程序模块。

2.配置入口文件:

//config.js中
requirejs.config({
  baseUrl: './js',                   //js主文件夹路径
  paths: {                           //对应所需文件路径
    jquery: 'plug/jquery-3.1.0.min', //省略后缀.js
    bootstrap: 'plug/bootstrap.min',
    main: 'control/main',
    greet: 'control/greet'           //非AMD格式js
  },
  shim: {                             //引用非AMD格式js文件内的函数
    // hello: { exports: 'hello' }    //exports 只引用非AMD格式js文件内的一个函数
    greet:{
        init: function(){             //init 引用非AMD格式js文件内的多个函数
            return {
                name2: 'name',
                sex: 'sex'
            }
        }
    }
  },
  map: {
        '*': {
            'css': 'plug/require-css.min'
        }
    }
});

requirejs(['main','greet'],function(main){
    main.alertCont(3);
    main.add(3,5);
    $('.name').text(main.name);
    name('孙中山');
    sex('男');
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

*exports 可以把某个非requirejs方式的代码中的某一个全局变量暴露出去,当作该模块以引用,但如果我要同时暴露多个全局变量时,则需要用到init。 
*当 exports 与 init 同时存在的时候, exports 将被忽略。

//main.js中(AMD格式js)
define(['jquery','css!../css/style.css'],function(){
    return { //返回对象
        alertCont : function(cont){
            console.log(cont);
        },
        add : function(x,y){
            $('.num').text(x+y);
        },
        name : 'lidysun',
    }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
//greet.js(非AMD格式js)
function name(name) {
  console.log('姓名:' + name);
}
function sex(sex) {
  console.log('性别:' + sex);
}
...

猜你喜欢

转载自blog.csdn.net/hahahhahahahha123456/article/details/80211251