AMD,CMD,UMD 三种模块规范 写法格式

一下三块均以 foo.js 为示例文件名,以 jQuery,underscore 为需求组件

ADM:异步模块规范, RequireJs 的支持格式

 1 // 文件名: foo.js
 2 define(['jquery', 'underscore'], function ($, _) {
 3 // 方法
 4 function a(){}; // 私有方法,因为没有被返回(见下面)
 5 function b(){}; // 公共方法,因为被返回了
 6 function c(){}; // 公共方法,因为被返回了
 7      //    暴露公共方法
 8     return {
 9         b: b,
10         c: c
11     }
12 });

 

CommonJs:node 的支持格式

 1 //    文件名: foo.js
 2 var $ = require('jquery');
 3 var _ = require('underscore');
 4  
 5 //    methods
 6 function a(){};    //    私有方法,因为它没在module.exports中 (见下面)
 7 function b(){};    //    公共方法,因为它在module.exports中定义了
 8 function c(){};    //    公共方法,因为它在module.exports中定义了
 9  
10 //    暴露公共方法
11 module.exports = {
12     b: b,
13     c: c
14 };

 

UMD:通用模式,支持以上两种格式,切可以支持老式的 “全局变量” 规范

 1 (function (root, factory) {
 2     if (typeof define === 'function' && define.amd) {
 3         // AMD
 4         define(['jquery', 'underscore'], factory);
 5     } else if (typeof exports === 'object') {
 6         // Node, CommonJS之类的
 7         module.exports = factory(require('jquery'), require('underscore'));
 8     } else {
 9         // 浏览器全局变量(root 即 window)
10         root.returnExports = factory(root.jQuery, root._);
11     }
12 }(this, function ($, _) {
13     //    方法
14     function a(){};    //    私有方法,因为它没被返回 (见下面)
15     function b(){};    //    公共方法,因为被返回了
16     function c(){};    //    公共方法,因为被返回了
17  
18     //    暴露公共方法
19     return {
20         b: b,
21         c: c
22     }
23 }));

 

原文地址:http://web.jobbole.com/82238/

 

转载于:https://www.cnblogs.com/s-qiu/p/7193875.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值