CommonJS的模块规范 转

转自:https://www.cnblogs.com/tianxintian22/p/5084870.html

CommonJS对模块的定义十分简单,主要分为模块引用、模块定义和模块标识。

1、模块引用

var math = require('math');//这个方法接受模块标识,以此引入一个模块的API到当前上下文中。

2、模块定义

对应引入的功能,上下文提供了exports对象用于导出当前模块的方法或者变量,并且它是唯一的出口。在模块中,存在一个module对象,它代表模块自身,而exports是module的属性。在Node中,一个文件就是一个模块,将方法挂载在exports对象上作为属性即可定义导出的方式。

//math.js
exports.add = function(){
    var sum = 0,
       i = 0,
       args = arguments,
       l = args.length;
    while (i < l){
        sum += args[i++];   
    }
    return sum;
};
//program.js
var math = require('math');//require()返回的对象实际上是exports
exports.increment = function(val){
    return math.add(val, 1);
}

3、模块标识

模块标识就是传递给require方法的参数,必须符合小驼峰命名的字符串,或者以.、..开头的相对路径,或者绝对路径。它可以没有文件名后缀.js。

CommonJS构建的模块导出和导入机制使得用户完全不必考虑变量污染。

点赞
  1. 1winded说道:
    Google Chrome Windows 10
    https://t.me/site_official_1win/255
  2. 1winded说道:
    Google Chrome Windows 10
    https://t.me/s/site_official_1win/360
  3. AllInAce说道:
    Google Chrome Windows 10
    https://t.me/s/iGaming_live/4864
  4. Pokerdomded说道:
    Google Chrome Windows 10
    https://t.me/s/officials_pokerdom/3559
  5. beefcasino说道:
    Google Chrome Windows 10
    https://t.me/s/BEeFCASiNO_OffiCiAlS
  6. LuckyBandit说道:
    Google Chrome Windows 10
    https://t.me/s/beefcasIno_oFfIciALS
  7. LuckyBandit说道:
    Google Chrome Windows 10
    https://t.me/s/beEFcASiNO_oFfIcIAls

发表回复

电子邮件地址不会被公开。必填项已用 * 标注