01前端/JS - 模块(cjs, amd, umd, esm)

CommonJS

介绍

主要在浏览器之外地方(例如服务器和桌面应用上)使用的模块化技术。

规范

一个文件就是一个模块,拥有单独的作用域。

定义模块

使用 exports 或 module.exports

1
2
3
4
var myModule = (a, b)=>{
return a+b;
}
module.exports = myModule;

使用模块

使用 require

1
var mm = require('./myModul.js');

AMD

介绍

主要在浏览器使用,因为和 CommonJS 在某些方面意见不合而独立出来(主要是模块定义方面)。

规范

一个文件就是一个模块,拥有单独的作用域。

定义模块

使用 define

amdjs-api/AMD.md at master · amdjs/amdjs-api

使用模块

使用 require

require · amdjs/amdjs-api Wiki

UMD

1
2
3
4
5
6
7
8
9
10
11
12
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.YourModuleName = factory());
}(this, (function () {
'use strict';

var yourModule = {};
// ...
return yourModule;

})));

ES6 Modules

现在浏览器们才刚刚开始去实现这个功能。但它在许多转换器中已经实现,例如 Traceur Compiler , Babel , Rollup 或 Webpack。