第二阶段: CommonJS规范 | |
| CommonJS就是一个JavaScript模块化的规范,该规范最初是用在服务器端的node的,前端的webpack也是对CommonJS原生支持的。
|
| 优点:
|
| 缺点:
|
| 特点
|
在浏览器中使用 CommonJS | |
| 由于浏览器不支持 CommonJS 规范,因为其根本没有 module、exports、require 等变量, 如果要使用,则必须转换格式。 Browserify是目前最常用的CommonJS格式转换的工具, 我们可以通过安装browserify来对其进行转换. 但是我们仍然需要注意,由于 CommonJS 的规范是阻塞式加载,并且模块文件存放在服务器端,可能会出现假死的等待状态(浏览器在一直下载文件) |
|
|
| 编译
|
| 或者引入
|
| node中的CommonJS |
// 示例一
// 文件名: foo.js
var $ = require('jquery');
var _ = require('underscore');
// methods
function a(){}; // 私有方法,因为它没在module.exports中 (见下面)
function b(){}; // 公共方法,因为它在module.exports中定义了
function c(){}; // 公共方法,因为它在module.exports中定义了
// 暴露公共方法
module.exports = {
b: b,
c: c
};
// 示例二
// 模块定义
// CommonJS 的规范说明,一个单独的文件就是一个模块,也就是一个单独的作用域。并且模块只有一个出口,module.exports/exports.xxx
// lib/math.js
const NAME='Nealayng';
module.exports.author = NAME;
module.exports.add = (a,b)=> a+b;
// 加载模块
// 加载模块使用 require 方法,该方法读取文件并且执行,返回文件中 module.exports 对象
// main.js
const mathLib = require('./lib/math');
console.log(mathLib.author);//Nealyang
console.log(mathLib.add(1,2));// 3