commonJS

/ / export
let name = 'liuhuang'
module.exports={
    name
}
exports.name = 'liuhuang'

/ / import
let obj = require('url')
console.log(obj.name)

//browserify
requireThe basic function of the command is to read and execute a JavaScript file, and then return the module'sexportsObject. If the specified module is not found, an error is reported.Copy the code

AMD

// Define dependent modules
define(['dataService'].function(dataService) {
  let name = 'Tom'
  function showMsg() {
    alert(dataService.getMsg() + ', ' + name)
  }
  // Expose the module
  return { showMsg }
})

/ / the main js file
(function() {
  require.config({
    baseUrl: 'js/'.// The starting point of the basic path is in the root directory
    paths: {
      // Mapping: module id name: path
      alerter: './modules/alerter'.// You can't write alerter.js here
      dataService: './modules/dataService'}})require(['alerter'].function(alerter) {
    alerter.showMsg()
  })
})()

/ / index. The HTML file<! DOCTYPE html><html>
  <head>
    <title>Modular Demo</title>
  </head>
  <body>
    <! -- import require.js and specify the entry to the JS main file -->
    <script data-main="js/main" src="js/libs/require.js"></script>
  </body>
</html>
Copy the code

CMD

// Define dependent modules
define(function(require.exports.module){
  // Import dependent modules (synchronization)
  var module2 = require('./module2')
  // Introduce dependency modules (asynchronous)
    require.async('./module3'.function (m3) {})// Expose the module
  exports.xxx = value
})
// Import dependent modules
define(function (require) {
  var m1 = require('./module1')
  var m4 = require('./module4')
  m1.show()
  m4.show()
})
Copy the code

ES6

/** Define the module math.js **/
var basicNum = 0;
var add = function (a, b) {
    return a + b;
};
export { basicNum, add };
/** Reference module **/
import { basicNum, add } from './math';
function test(ele) {
    ele.textContent = add(99 + basicNum);
}


// Define the module
export default function () {
  console.log('foo');
}
// Reference module
import customName from './export-default';
customName(); // 'foo'
Copy the code

Differences between ES6 modules and CommonJS modules

  1. The CommonJS module outputs a copy of the value, and the ES6 module outputs a reference to the value.
  2. The CommonJS module is a runtime load, and the ES6 module is a compile-time output interface.

Differences between CMD and AMD

AMD advocates dependency forward and early execution, while CMD advocates dependency near and late execution.