RequireJS

quirejs : http://www.requirejs.cn/

叶小钗  : http://www.cnblogs.com/yexiaochai/p/3214926.html

app.js 展示:

 1 //<script data-main="js/app.js" src="js/require.js"></script> 页面引入;
 2 
 3 requirejs.config({
 4     baseUrl: 'js',                                  // 所有模块的查找根路径;
 5     paths: {                                        // 快捷路径;
 6         js  : 'js',  
 7         logo: 'logo',
 8         lib : 'lib'
 9     },
10      shim: {                                        // 声明依赖关系;
11           'jquery.fixedHead': {                      //插件的名字;
12             deps: ['jquery'],                       //需要加载的依赖项的数组;
13             exports: 'fixedHead',                   //自己写的小插件的别名,需要依附于Jquery;
14             init :function (bar) {                  //承接库加载后的初始工作,说白了就是处理插件没有define包成块的模块;
15                 return this.fixedHead.noConflict();
16             }
17         }
18      },
19      map: {                                         //用来解决同一个模块的不同版本问题;
20         'A': {
21             'jquery': 'jquery-1.6.4'
22         },
23         'B': {
24             'jquery': 'jquery-1.7.2'
25         }
26     },
27      scriptType :'text/javascript;version=1.8',    //指定RequireJS将script标签插入document时所用的type=""值;
28      context : ['footer']                          //指定要加载的一个依赖数组;
29 });
30 
31 //常用也就这些;
32 
33 requirejs(['lib/jquery-1.8.3.min','logo/logo','fixed-head'],
34 function   ($,logo) {
35   
36 });

logo.js 展示:

 1 define(['lib/head','index'],function(head,index) {   //依赖注入到模块     
 2     var headJson = head;
 3 
 4      var cssUrl = require.toUrl("../css/base.css"); //生成相对于模块的URL地址;
 5      console.log(cssUrl);                   //执行这个地址;
 6      console.log( headJson.h );            //执行lib/head.js 里的h方法;
 7 
 8      return {                           // 对外输出的方法;
 9         show : function(){
10             alert('你就没登陆');
11         }
12      }
13         
14 });

requirejs 模块可以转成commonjs 模块

head.js 展示:

 1 define(function(require, exports, module) {
 2 
 3     var c = require('../common');
 4     
 5     console.log( c.aa() );
 6 
 7     return {
 8        h : 'head.js'
 9     }
10 
11 });

common.js 代码展示:

1 define(function(require, exports){
2     exports.aa = function(){
3         
4         return 'common.js';
5 
6     }
7 });

后记:

注意初始化的 baseUrl 根目录的位置,剩下都和 sea.js差不多 还能转化成sea.js。

原文地址:https://www.cnblogs.com/auok/p/5045481.html