commonJS & AMD

109 阅读1分钟

commonJS用法(同步加载)

var express = require(’express‘)
//math.js
function add(a, b) {
    return a + b
}
module.exports = {
    add
}
//使用
var math = require('math')
math.add(1,2)

commonJS特点

同步的方式加载模块,适用于nodejs,因为服务端文件存在磁盘,所以读取很快,但是对于浏览器端,网络原因等,只能使用异步加载。

AMD(Asynchronous Module Definition)用法(异步加载)

首先可以看下,不使用AMD,模块相互引用的实现:

// main.html
<body></body>
//main.js中调用了alertMsg, alertMsg调用了serviceData.js,所以在引用js的时候需要严格遵循先后顺序<script src="serviceData.js"></script><script src="alertMsg.js"></script><script src="main.js"></script>


// serviceData.js
(function(window) {  let name = '张三'  function getName() {    return name  }  window.serviceData = getName})(window)


// alertMsg.js
(function(window, serviceData) {  let data = serviceData()  function alertMsg() {    console.log("alert", data)  }  window.alertMsg = alertMsg})(window, serviceData)


// main.js
(function(alertMsg) {  alertMsg()})(alertMsg)

使用AMD引用模块

// main.js
// define定义模块
define('math',function() {  var add = function(a, b) {    return a + b  }  return {    add  }})
// require引用模块
require(['math'], function(math) {  console.log("amd模块打印", math.add(1,2))})

CMD

AMD依赖前置,提前加载

CMD依赖就近,推迟加载

ES6 Module

import 引入模块, export 导出模块

commonJS与ES6比较

commonJS

  • 运行时加载
  • 输出值得拷贝,模块内部变化不会影响到值

ES6

  • 编译时加载
  • 输出的是值的引用