The development process

CommonJS, AMD, CMD, Requeir, Moudle. Exports, exports, exports… Blast in place…

Let’s get a sense of the timeline for these specifications

  • 2009 -> CommonJS
  • 2010 -> AMD specification
  • 2011 -> CMD specification
  • 2015 -> ES6 Module

CommonJS

The CommonJS specification is an early adopter. It was started by Mozilla engineer Kevin Dangoo in 2009. The CommonJS specification was designed to run JS in more places, mainly on the server side.

Usage examples

Module. Exports or exports are responsible for disclosure of data, require to introduce

<! --a.js--> module.exports = {name: 'name'} <! Exports --> <! --export. Name = 'name '--> <! --b.js--> const res = require('./a.js') console.log(res.nameCopy the code
Module. Exports

At first glance, it might seem that CommonJS provides two ways to export data. In fact, require doesn’t know about exports, and it works well because of the functionality of the code inside the module.

var module = { exports: { <! }} var exports = module.exports return module.exportsCopy the code

Exports is a reference to module. Exports is a reference to exports.

For example, <! --a.js--> exports = {name: 'exports'} --a.js--> exports = {name:' name 'Copy the code

AMD (Asynchronous Module Definition)

The AMD specification was introduced in 2010 by requireJS. The CommonJS specification is designed to compensate for the modularity mechanism on the server side. Unlike the server, which loads quickly and has to wait while the client loads, the CommonJS specification can be suspended in motion. The callback function is executed after the dependency has been loaded.

define([module-name?] , [dependencies?] , [factory])

  • Module-name: a string, module name (optional)
  • Dependencies: Dependencies module (optional) to load
  • Factory: factory method that returns a module function
<! -- Define module --> <! --> define('module', ['dep1', 'dep2'], function(dep1, 'function') Dep2) {function foo () {dep1. DoSomething (); Dep2. DoSomething (); } return {foo: foo}; }) <! Select * from array where you want to load the module. Function (module){module.foo()}); / / require(['module'], function(module){module.foo()});Copy the code

CMD (Common Module Definition)

The CMD specification was introduced by seaJS in 2011. The CMD specification is similar to the AMD specification. The main difference is that the CMD specification loads dependencies nearby and delays execution until required.

<! -- a.js --> define(function(require, exports, module) { function foo(){ <! Var dep1 = require('dep1') dep1.dosomething (); var dep1 = require('dep1') dep1.dosomething (); } <! } --> exports. Foo = foo /** return {foo: foo}; * * /}); <! -- b.js --> seajs.use("./a", function(a){ a.foo() });Copy the code

ES6 Module

In 2015, ES6 came out and introduced new features such as the ES Module, such as export, import and so on.

Es6 module is more common, post a ruan yifeng es6 link ES6 Module


Finally, merry Christmas ~