一、node模块化机制 
1、commonJS模块规范包括三部分:模块引用、模块定义、模块标识。例如:
//math.js
exports.add = function(){
    var sum = 0;
    var args = arguments;
    var len = args.length;
    for(var i = 0;i < len;i++){
        var num = args[i];
        sum += num;
    }
    return sum;
}
 
 
// increment.js
var math = require('./math');
exports.increment = function(val){
    return math.add(val, 1);
};
 
 
// app.js
var increment = require('./increment.js');

console.log(increment.increment(5));
 
注意:模块标识符就是传递给require方法的参数,可以是./ 或者 ../ 开头的相对路径,也可以是 / 开头的绝对路径。
 
2、node实现了commonJS模块规范,同时引入了自己的特性。node引入模块需要经历一下三个步骤:
(1)、路径分析
(2)、文件定位。可以没有拓展名,如果没有拓展名,node将按照.js .node .json的顺序定位文件。
(3)、编译执行。
 
node中有两种模块:
(1)、核心模块(node自身提供)node进程启动时,会载入部分核心模块。 
(2)、文件模块(用户编写)。第一次编译执行文件模块后,node以文件路径作为索引,将该模块对象缓存在Module._cache对象上。
 
3、commonJS包规范
目录结构:
package.json 包描述文件
bin 二进制可执行文件
lib JS代码目录
doc 文档
test 测试用例
 
4、基于commonJS包规范node有了npm npm的常用命令:npm install express可安装express框架
 
5、由于前端受网络环境的限制commonJS规范并不适用于前端。于是有了AMD。实现了AMD规范的JS库:require.js,curl.js
 
require.js 核心代码:
(function () {
    require.load = function (context, moduleName, url) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                eval(xhr.responseText);
                //Support anonymous modules.
                context.completeLoad(moduleName);
            }
        };
    };
}());

 
curl.js核心代码:

loadScript: function (def, success, failure) {
// script processing rules learned from RequireJS
// TODO: pass a validate function into loadScript to check if a success really is a success

// insert script
var el = doc.createElement('script');

// initial script processing
function process (ev) {
ev = ev || global.event;
// detect when it's done loading
// ev.type == 'load' is for all browsers except IE6-9
// IE6-9 need to use onreadystatechange and look for
// el.readyState in {loaded, complete} (yes, we need both)
if (ev.type == 'load' || readyStates[el.readyState]) {
delete activeScripts[def.id];
// release event listeners
el.onload = el.onreadystatechange = el.onerror = ''; // ie cries if we use undefined
success();
}
}

function fail (e) {
// some browsers send an event, others send a string,
// but none of them send anything useful, so just say we failed:
failure(new Error('Syntax or http error: ' + def.url));
}

// set type first since setting other properties could
// prevent us from setting this later
// actually, we don't even need to set this at all
//el.type = 'text/javascript';
// using dom0 event handlers instead of wordy w3c/ms
el.onload = el.onreadystatechange = process;
el.onerror = fail;
// js! plugin uses alternate mimetypes
el.type = def.mimetype || 'text/javascript';
// TODO: support other charsets?
el.charset = 'utf-8';
el.async = !def.order;
el.src = def.url;

// loading will start when the script is inserted into the dom.
// IE will load the script sync if it's in the cache, so
// indicate the current resource definition if this happens.
activeScripts[def.id] = el;

head.insertBefore(el, insertBeforeEl);

// the js! plugin uses this
return el;

}
 
二、前端脚本按需加载方式:
1、创建XMLHttpRequest对象获取JS文件,用eval方法执行完毕后,执行回调。(require.js) 存在跨域问题。
2、动态创建<script>标签,同时绑定onload onreadystatechange方法执行回调。(curl.js)
 

node模块机制的更多相关文章

  1. Nodejs:Node.js模块机制小结

    今天读了<深入浅出Nodejs>的第二章:模块机制.现在做一个简单的小结. 序:模块机制大致从这几个部分来讲:JS模块机制的由来.CommonJS AMD CMD.Node模块机制和包和n ...

  2. 深入浅出node(2) 模块机制

    这部分主要总结深入浅出Node.js的第二章 一)CommonJs 1.1CommonJs模块定义 二)Node的模块实现 2.1模块分类 2.2 路径分析和文件定位 2.2.1 路径分析 2.2.2 ...

  3. Node.js入门:模块机制

    CommonJS规范      早在Netscape诞生不久后,JavaScript就一直在探索本地编程的路,Rhino是其代表产物.无奈那时服务端JavaScript走的路均是参考众多服务器端语言来 ...

  4. 《深入浅出Node.js》第2章 模块机制

    @by Ruth92(转载请注明出处) 第2章 模块机制 JavaScript 先天缺乏的功能:模块. 一.CommonJS 规范: JavaScript 规范的缺陷:1)没有模块系统:2)标准库较少 ...

  5. 模块机制 之commonJs、node模块 、AMD、CMD

    在其他高级语言中,都有模块中这个概念,比如java的类文件,PHP有include何require机制,JS一开始就没有模块这个概念,起初,js通过<script>标签引入代码的方式显得杂 ...

  6. Node.js之模块机制

    > 文章原创于公众号:程序猿周先森.本平台不定时更新,喜欢我的文章,欢迎关注我的微信公众号. ![file](https://img2018.cnblogs.com/blog/830272/20 ...

  7. Node解析之----模块机制篇

    开篇前,我们先来看张图, 看node与W3C组织.CommonJS组织.ECMAScript之间的关系. Node借鉴来CommonJS的Modules规范实现了一套非常易用的模块系统,NPM对Pac ...

  8. node模块加载层级优化

    模块加载痛点 大家也或多或少的了解node模块的加载机制,最为粗浅的表述就是依次从当前目录向上级查询node_modules目录,若发现依赖则加载.但是随着应用规模的加大,目录层级越来越深,若是在某个 ...

  9. 通过Anuglar Material串串学客户端开发 - NodeJS模块机制之Module.Exports

    module.exports 前文讲到在Angular Material的第二个编译文件docs/gulpfile.js中却看到了一个奇怪的东西module.exports那么module.expor ...

随机推荐

  1. ECS简介

    https://www.cnblogs.com/yangrouchuan/p/7436533.html Unity下的ECS框架 Entitas简介   最近随着守望先锋制作组在gdc上发布的一个关于 ...

  2. dedecms图片绝对路径(附件绑定域名)的设置方法

    dedecms默认的附件路径使用的是相对路径,但是在实际应用,我们可能会需要让文章的图片附件显示绝对地址,解决方案如下: 1.打开include目录下的文件extend.func.php,添加函数re ...

  3. H5教程(二),CSS入门(一)选择器

    这是我的第二篇博客,H5教程CSS入门,适合刚开始学习H5的新手,让我们共同进步. 1.  CSS简介 1.1  CSS是什么? CSS称为样式层叠表,是用于增强或控制网页样式,并允许将样式信息与网页 ...

  4. anularjs前端分页

    var dataList = []; $scope.page = { page:1, pageSize:15, numPerPageOpt:[15,30,50,100], totalNum:0, to ...

  5. Necklace of Beads POJ - 1286

    \(\color{#0066ff}{ 题目描述 }\) 一个圈上有n个珠子,有三种颜色可以染,问本质不同的方案数(通过旋转和翻转重合的算一种) \(\color{#0066ff}{输入格式}\) 多组 ...

  6. 数据结构13: 括号匹配算法及C语言实现

    在编写代码的时候,经常会用到两种括号:圆括号 “()” 和大括号 “{}” .不管使用哪种括号,程序编译没有问题的其中一个重要因素就是所使用的括号是否能够匹配上. 在编写程序时,括号可以嵌套,即: “ ...

  7. FPGA实战操作(1) -- SDRAM(操作说明)

    SDRAM是做嵌入式系统中,常用是的缓存数据的器件.基本概念如下(注意区分几个主要常见存储器之间的差异): SDRAM(Synchronous Dynamic Random Access Memory ...

  8. 07. 如何实现移动端rem适配

    如何实现移动端rem适配 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...

  9. restframework 的一些操作

    路飞学城项目: 1 Vue 2 restframework框架(一周) 3 学城项目(一周-两周) day98 1 CBV(class based view) 与 FBV(function based ...

  10. my.资质

    换算到每1点魔力初始,1点魔力等同于22点法资,等于0.00235点成长. 气血=等级*体力资质*0.002895+体力属性点*成长*7 魔法=等级*法力资质*0.002085+法力属性点*成长*5 ...