一、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. 接口和抽象类有什么区别(Java基础)

    接口可以多实现 Java中抽象类只能单继承 接口   相对于类来说    可以实现多个接口 抽象相对于 类来说 只能单一继承 一个类只能继承一个抽象类,但可以实现多个接口. 抽象类中可以包含抽象方法和 ...

  2. kuangbin专题16I(kmp)

    题目链接: https://vjudge.net/contest/70325#problem/I 题意: 求多个字符串的最长公共子串, 有多个则输出字典序最小的. 思路: 这里的字符串长度固定为 60 ...

  3. Cannot find module 'webpack/bin/config-yargs'

    1.版本不兼容 npm install webpack-dev-server@1.15.0 -g

  4. srs录制视频时间戳有点问题

    srs2或者srs3目前最新的版本和之前的版本,使用dvr功能录制flv文件.使用本地播放器,如ffplay.potplayer.vlc.KMP和MPV等,都是正常的播放完整视频.但是使用web fl ...

  5. P2389 电脑班的裁员

    题意:长度为n的序列,选出k个连续的字段,使和最大(有负数) 暴力只选正数且不考虑k的边界问题50(数据...) 正解从$O(n^3)到O(n)$不等,($O(n)$不会) DP 1.$O(n^3)$ ...

  6. 10大Python开源项目推荐(Github平均star2135)

    翻译 | suisui 来源 | 人工智能头条(AI_Thinker) 继续假日充电系列~本文是 Mybridge 挑选的 10 个 Python 开源项目,Github 平均star 2135,希望 ...

  7. Oulipo (KMP出现次数)

    The French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter 'e ...

  8. Codeforces Round #334(div.2)(新增不用二分代码) B

    B. More Cowbell time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...

  9. java读取配置到Hash表里

    import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; im ...

  10. MetricStatTimer

    package org.apache.storm.metric.internal; import java.util.Timer; /** * Just holds a singleton metri ...