1. 程式人生 > 其它 >前端模組化規範小結(commonJS 、ES6模組化)

前端模組化規範小結(commonJS 、ES6模組化)

1. 前端模組化規範主要有:

  • commonJS 規範
  • AMD規範
  • CMD 規範
  • ES6 規範

實際上,前三種模組化規範現在已經不流行了,ES6模組化規範就相當於可以取代前三者了。

本文主要講講 commonJS 規範和  ES6模組化規範。

2. commonJS 規範

概述:

commonJS 規範起初被提出用在伺服器端的,並命名為 serverJS,後來為了體現它的廣泛應用性,改為 commonJS。

commonJS  規範的模組中,所有變數和函式都是私有的。

commonJS 規範規定,每個模組中有一個 module 變數,代表了當前模組。

module 是一個物件,它有個 exports 屬性(即 module.exports )代表改模組向外提供的介面。

載入某個模組,其實是載入該模組的module.exports屬性。

外部模組需要載入某一模組的時候用 require 來載入。

在伺服器端,模組的載入是執行時同步載入的;在瀏覽器端,模組需要提前編譯打包處理。

所有程式碼都執行在模組作用域,不會汙染全域性作用域。

模組可以多次載入,但是隻會在第一次載入時執行一次,然後執行結果就被快取了,以後再載入,就直接讀取快取結果。要想讓模組再次執行,必須清除快取。

模組載入的順序,按照其在程式碼中出現的順序。

node.js 正是遵循 commonJS 模組化規範的。在 node 中,一個JS檔案就為一個模組。

另外,exports 和 module.exports 是全等的,因為 node.js 內部程式碼中規定  module.exports = exports

。但是,兩者同時存在時,以 module.exports 匯出物件為準。

下面上程式碼演示:

// mod1.js
const name = "哈哈哈";
const age = 18;
 
let message = "hello javascript";
function sayHello() {
    console.log('幹嘛')
}
 
exports.name = name;
exports.age = age;
exports.sayHello = sayHello;
 
module.exports = {
    name: "嘻嘻嘻",
    age: 20,
    sayHello:  function() {
        console.log('你好')
    }
}

// mod2.js
const m1 = require("./mod1.js");
 
console.log(m1.name); // 嘻嘻嘻
console.log(m1.age);  // 20
m1.sayHello();  // 你好
 
// 也可以直接將匯出物件解構獲取變數
// const { name, age, sayHello } = require("./bar");
 
// console.log(name);
// console.log(age);
// sayHello();

3. ES6 模組化

https://www.cnblogs.com/suihung/p/16153213.html

4.  commonJS 與 ES6 模組化 的區別

① CommonJS 模組輸出的是一個值的拷貝,ES6 模組輸出的是值的引用。

② CommonJS 模組是執行時載入,ES6 模組是編譯時輸出介面。

CommonJS模組的載入機制是,輸入的是被輸出的值的拷貝。也就是說,一旦輸出一個值,模組內部的變化就影響不到這個值。