入門webpack( 一)關於模塊化

1.爲何須要模塊化javascript

可能不少同窗是經過index.html,style.css,demo.js接觸進入前端開發的,但在實際項目中會複雜的多,開發者爲了重複造輪子對經常使用的實現進行封裝實現了一個庫,後來的開發者爲了不重複造輪子想使用其餘開發者已經造好的輪子,可是直接引用他人的庫可能會形成變量污染和衝突。
一種解決方式是命名空間。css

var NameSpace = {}
NameSpace.type = NameSpace.type || {}
NameSpace.type.method = function() {...}

採用命名空間能夠避免變量衝突污染等問題,但缺點是在使用起來不方便,須要記住如上圖所示的鏈式關係。但javascript自己缺乏模塊化的概念。爲了彌補這個缺點,衆多規範由此產生。html

2 . 關於規範
CommonJS 前端

JavaScript is a powerful object oriented language with some of the fastest dynamic language interpreters around. The official JavaScript specification defines APIs for some objects that are useful for building browser-based applications. However, the spec does not define a standard library that is useful for building a broader range of applications.java

The CommonJS API will fill that gap by defining APIs that handle many common application needs, ultimately providing a standard library as rich as those of Python, Ruby and Java. The intention is that an application developer will be able to write an application using the CommonJS APIs and then run that application across different JavaScript interpreters and host environments. With CommonJS-compliant systems, you can use JavaScript to write:node

Server-side JavaScript applications
Command line tools
Desktop GUI-based applications
Hybrid applications (Titanium, Adobe AIR)

上圖是官網對於CommonJS的介紹。能夠看到Javascript官方規範只定義了一些構建基於瀏覽器程序的對象API,但規範並無定義一個標準庫,而這個庫對於構建更普遍的應用程序是有效的。git

CommonJS API將經過定義處理許多常見應用程序需求的API來填補這一空白,最終提供一個與Python、Ruby和Java同樣豐富的標準庫。而開發者利用這個庫能作什麼呢?github

  • 服務端JS應用
  • 命令行工具
  • 桌面應用
  • 混合應用

能夠看到CommonJS旨在定義一個標準,開發人員經過遵照這個標準可使JS實現更多的東西。web

CommonJS主要針對服務端,nodeJS是基於CommonJS標準實現的。二者之間相互印證,共同發展。api

CommonJS有如下特色,一個文件爲一個模塊,經過module.exports對外暴露接口,經過require實現模塊相互引用。各個模塊之間相互獨立,經過暴露的接口能夠實現模塊相互訪問。

AMD(Async Module Definition)規範
參考1:AMD
參考2:前端模塊化的發展史
特色

  • 使用define定義模塊
  • 使用require加載模塊
  • 依賴前置,提早執行
  • requireJS

CMD(Common Module Definition)
官網:CMD

特色

  • 一個文件定義一個模塊

  • 使用define定義模塊

  • 使用require加載模塊

  • 儘量懶執行

UMD(Universal Module Definition)
UMD規範旨在提供一種通用解決方案,是否支持AMD,不支持判斷是否支持CommonJS?不支持則採用全局變量的方式。

ES6 Modules

特色:

  • 一個文件爲一個模塊

  • export 提供對外接口

  • import 導入其餘模塊

總結:爲了應對各類需求,模塊發開發成爲必不可少的,在模塊化開發演變的歷史中,衍生了各類規範,每種規範都有其標誌性的產品。

  • CommonJS 服務端 同步執行 NodeJS
  • AMD 瀏覽器端 依賴前置,提早執行 require.JS
  • CMD 瀏覽器端 懶執行 sea.JS
相關文章
相關標籤/搜索