AMD#
AMD (Asynchronous Module Definition) is a module definition specification that is primarily used for the browser. Its main feature is that dependencies must be declared in advance.
define('./index.js', function(code) {
// code is the content returned by index.js
});
CMD#
CMD (Common Module Definition) is a module definition specification that is also primarily used for the browser. Its main feature is that it supports dynamically importing dependent files.
define(function(require, exports, module) {
var indexCode = require('./index.js');
});
UMD#
UMD (Universal Module Definition) is a module definition specification that is compatible with both AMD and CommonJS module syntax.
webpack(require.ensure): Code splitting in webpack 2.x version.
CommonJS#
CommonJS is the built-in module system in Node.js. It includes the following features:
- require: supports importing modules
- module.exports: exports multiple variables
- exports: exports variables one by one
// Built-in module in Node.js: require
const fs = require('fs');
// Built-in module in Node.js: module.exports, exports
const EventEmitter = require('events');
module.exports = new EventEmitter();
// Do some work and emit the 'ready' event from the module itself after a certain period of time.
setTimeout(() => {
module.exports.emit('ready');
}, 1000);
ES Modules#
The export and import commands are used as follows:
export: exports the module variables you define
import: imports a module variable
// ES6 export: export a.js file - export { one, two }
export default three
// ES6 import: import file - import { one, two } from 'a.js'