requireJS的匿名模組和命名模組的差別和最佳實務
requirejs是一個簡單的javascript架構,支援模組化編碼和模組的非同步載入。
在requireJS中模組可以分為:匿名模組和命名模組這2種。
requireJS定義一個匿名模組
define(function(){ return {id:"noName"};});
requireJS定義一個命名模組
define("constantModule",[],function(){ return {id:"hasName"};});
requireJS官網上也說: It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names。就是說推薦使用匿名模組。
jquery從1.7版本開始支援AMD(Asynchronous Module Definition),並且是一個命名模組,模組名就是jquery,我使用的是jquery-1.11.1.js,源碼如下:
if ( typeof define === "function" && define.amd ) {define( "jquery", [], function() {return jQuery;});}
現在看下使用requireJS架構載入jquery,只要路徑是正確的,下面代碼是能夠正確載入jquery的。
require.config({baseUrl:"./../", paths: { jquery: 'jquery-1.11.1' }});//jquery架構的模組名是jquery,這裡不能修改,不然載入不成功require(["jquery"], function(jq) {//如果載入成功,應該顯示1.11.1 alert(jq().jquery);});
上面的代碼能夠正常載入jquery架構之後,我們稍微修改下上面的代碼
require.config({baseUrl:"./../", paths: { jquery_name: 'jquery-1.11.1' }});//jquery架構的模組名是jquery,這裡不能修改,不然載入不成功require(["jquery_name"], function(jq) {//如果載入成功,應該顯示1.11.1 alert(jq().jquery);});可以發現,這次jquery架構不能正常載入。我們僅僅是改變了模組名而已。這裡可以得出一個結論:
如果是命名模組,那麼使用require載入該模組的時候,模組名一定要正確,不能隨意修改。
接下來我們載入自己定義的匿名模組和命名模組,驗證下我們的結論。
require.config({baseUrl:"./../", paths: { jquery: 'jquery-1.11.1', hehe: 'require_demo/module_noName', constantModule: 'require_demo/module_hasName', }});//jquery架構的模組名是jquery,這裡不能修改,不然載入不成功require(["jquery","hehe","constantModule"], function(jq,noName,hasName) { alert(jq().jquery);alert(noName.id);alert(hasName.id);});調整檔案路徑,保證上面的代碼能夠正常載入。接下來我們可以修改上面的代碼
require.config({baseUrl:"./../", paths: { jquery: 'jquery-1.11.1', xx: 'require_demo/module_noName', constantModule_hehe: 'require_demo/module_hasName', }});//jquery架構的模組名是jquery,這裡不能修改,不然載入不成功require(["jquery","xx","constantModule_hehe"], function(jq,noName,hasName) { alert(jq().jquery);alert(noName.id);alert(hasName.id);});可以發現:xx模組能夠正常載入,constantModule_hehe不能正常載入。我們可以看到:
匿名模組具有更大的靈活性,載入匿名模組的時候,名稱可以隨意指定。