前端模块化规范Commonjs/Amd/Cmd

简单描述下区别:html

Commonjs: 用于服务器端, 经过export导出模块,require加载模块,module表示模块自己,加载过程为同步, 不适合客户端. nodejs是用commonjs规范node

写法: a.js     var a = function(x) {console.log(x)};   module.export = a;服务器

    b.js     var b= reuqire('./a.js);   b('啦!!');异步

Amd: 常见实现库requirejs, 异步加载requirejs

写法: ui

// module1.js spa

define(htm

{blog

    methodA: function() {ip

  console.log('我是module1的methodA');

    },

    methodB: function() {

  console.log('我是module1的methodB');

    }

})

// module2.js

define(function () {

    return {

  methodA: function() {

    console.log('我是module2的methodA');

  },

  methodB: function() {

    console.log('我是module2的methodB');

  }

    };

});

// module3.js

define(['module1', 'module2'], function(m1, m2) {

    return {

  methodC: function() { m1.methodA(); m2.methodB();}

     };

});

// main.js

require(['module3'], function(m3){ m3.methodC(); });

 

// main.html

<script data-main="main" src="require.js"></script>

 

Cmd跟Amd相似

// CMD

define(function(require, exports, module) {

var a = require('./a');

a.doSomething();  // 此处略去 100 行

var b = require('./b');// 依赖能够就近书写

b.doSomething();

// ...

})

 

 

注: 参考 https://www.cnblogs.com/lishuxue/p/6000205.html

相关文章
相关标签/搜索