1. 程式人生 > 實用技巧 >JS模組化

JS模組化

前端模組化

  • 優點:模組化,按需載入、更好的分離、提高複用性和維護性

  • 缺點:請求數量過多、順序不能隨意切換;

演進過程

  • function模式;
    function a(){
        console.log();
    }
  • namespace模式; 但是屬性容易被更改,沒有私;直接暴漏在window上
    var obj = {
        age:88,
        say:function(){
             console.log();
        }
    }
  • IIFE(立即執行)模式; JQ為典型,傳入window為形參
   (function(w){
       w.age = {
            age:88,
            say:function(){
                console.log();
            }
       }
   })(window)

模組化規範

  1. Common.js

說明

特點 : 每個檔案都可以當作一個檔案;

node.js 基於此規範;

服務端:模組的載入時,執行去同步載入的,

瀏覽器端:模組需要提前打包處理;(不可能,執行時才去由瀏覽器傳送請求,會造成頁面卡頓、白屏、閃爍);require模組瀏覽器不支援

  • 暴露模組

    • module.exports = value;

    • exports.xxx = value;

    • exports 屬性本身就是空物件,暴漏的本質就是向此物件上加屬性或者覆蓋exports物件。

  • 引入模組

    • require(../xxx.js) 填入路徑 | 模組名

    • 第三方模組: xxx模組名

    • 自定義模組:xxx.js所在的檔案路徑

實現

  • 服務端: node環境自帶

  • 瀏覽器端:browserify 可以編譯專案使其支援require/module

  1. Amd (layUI)

說明:依賴reuquire.js https://requirejs.org/docs/api.html

  • 暴露模組
define(function(){
    return 模組;
})
  • 有依賴的模組
define(['module1','module2'],function(m1,m2){
    return 模組;
})
  • 引入模組
require(['module1','module2'],function(m1,m2){

})
  1. ES6

說明:

需要編譯打包處理;(有些語法不支援)

  • 引入 : import (import {module,module1} from './modules/modules'