cjs 是 common js 的缩写,CommonJS 是 Node.js 采用的模块化规范,主要用于服务端的 JavaScript 环境
// importing
const doSomething = require('./doSomething.js')
// exporting
module.exports = function doSomething(n) {
// do something
}
AMD 是 asynchronous module definition 的缩写,是一个在浏览器环境中使用的模块化规范。它解决了 CommonJS 在浏览器中同步加载的问题,使用异步加载方式来加载模块。
define(['dep1', 'dep2'], function (dep1, dep2) {
// define the module value by returning a value.
return function () {};
})
// or simplified CommonJS wrapping
define(function (require) {
var dep1 = require('dep1'),
dep2 = require('dep2');
return function () {};
})
// math.js
define([], function() {
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
return {
add,
subtract
};
});
// main.js
require(['./math'], function(math) {
console.log(math.add(1, 2)); // 输出: 3
console.log(math.subtract(5, 3)); // 输出: 2
});
UMD 是 Universal Module Definition 的缩写
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery', 'underscore'], factory);
} else if (typeof exports === 'objects') {
module.exports = factory(require('jquery'), require('underscore'));
} else {
root.Requester = factory(root.$, root._);
}
})(this, function ($, _) {
// this is where I defined my module implementation
var Requester = {// ... };
return Requester;
})
ESM 是 ES6 Module 的缩写。是 JavaScript 语言级别的模块系统,支持静态分析,能够在编译时确定模块的依赖关系。
import React from 'react';
export default function() {
// your function
}
export const function1() {}
export const function2() {}