Sea.js-模塊化開發框架

1、Sea.js和Grunt構建工具

  好處:javascript

  一、sea.js按需加載,用到哪些模塊會加載哪些模塊,節省http請求css

  二、解決模塊之間的依賴問題.html

  Grunt構建工具:能夠對文件進行壓縮和合並java

 

2、API 快速參考

1、seajs.config

用來對 Sea.js 進行配置。node

 1 seajs.config({
 2 
 3     // 設置路徑,方便跨目錄調用
 4     paths: {
 5         'arale': 'https://a.alipayobjects.com/arale',
 6         'jquery': 'https://a.alipayobjects.com/jquery'
 7     },
 8 
 9     // 設置別名,方便調用
10     alias: {
11         'class': 'arale/class/1.0.0/class',
12         'jquery': 'jquery/jquery/1.10.1/jquery'
13     }
14 
15 });

 

2、seajs.use

用來在頁面中加載一個或多個模塊。jquery

 1 // 加載一個模塊
 2 seajs.use('./a');
 3 
 4 // 加載一個模塊,在加載完成時,執行回調
 5 seajs.use('./a', function(a) {
 6     a.doSomething();
 7 });
 8 
 9 // 加載多個模塊,在加載完成時,執行回調
10 seajs.use(['./a', './b'], function(a, b) {
11     a.doSomething();
12     b.doSomething();
13 });

 

3、define

用來定義模塊。Sea.js 推崇一個模塊一個文件,遵循統一的寫法:git

1 define(function(require, exports, module) {
2 
3     // 模塊代碼
4 
5 });

require, exportsmodule 三個參數可酌情省略,具體用法以下。github

 

4、require

require 用來獲取指定模塊的接口。npm

1 define(function(require) {
2 
3     // 獲取模塊 a 的接口
4     var a = require('./a');
5 
6     // 調用模塊 a 的方法
7     a.doSomething();
8 });

注意,require 只接受字符串直接量做爲參數json

 

5、require.async

用來在模塊內部異步加載一個或多個模塊。

 1 define(function(require) {
 2 
 3     // 異步加載一個模塊,在加載完成時,執行回調
 4     require.async('./b', function(b) {
 5         b.doSomething();
 6     });
 7 
 8     // 異步加載多個模塊,在加載完成時,執行回調
 9     require.async(['./c', './d'], function(c, d) {
10         c.doSomething();
11         d.doSomething();
12     });
13 
14 });

 

6、exports

用來在模塊內部對外提供接口。

1 define(function(require, exports) {
2 
3     // 對外提供 foo 屬性
4     exports.foo = 'bar';
5 
6     // 對外提供 doSomething 方法
7     exports.doSomething = function() {};
8 
9 });

 

7、module.exports

exports 相似,用來在模塊內部對外提供接口。

1 define(function(require, exports, module) {
2 
3   // 對外提供接口
4   module.exports = {
5     name: 'a',
6     doSomething: function() {};
7   };
8 
9 });

module.exportsexports 的區別

 

以上 7 個接口是最經常使用的,要牢記於心。

 

---------------------------------------------------------------------------------------------------------------------------------------

 

4、seajs模塊依賴的加載處理

最近在作項目的時候發現一些關於模塊依賴問題,特記錄下:

好比現有3個文件:

 1 /*init.js*/
 2 define(function(require, exports, module){
 3     require('jquery');
 4     require('jquery.plugA');
 5 })
 6 
 7 /*jquery.plugA.js*/
 8 define(function(require, exports, module){
 9     require('jquery');
10     require('jquery.plugB');
11     //code...
12 })
13 
14 /*jquery.plugB.js*/
15 define(functioin(require, exports, module){
16     require('jquery');
17     //code...
18 })

  好比執行init.js時,init.js、jquery.plugA.js、jquery.plugB.js都會依賴到jquery,那麼這種狀況下seajs對jquery如何處理的呢?只執行一次?執行屢次?仍是其餘方式?

此處參考玉伯的回答:

我對模塊調用的理解是,調用是指獲取某個模塊的接口。在 SeaJS 裏,只有 seajs.use, require.async, 和 require 會產生

  模塊調用,好比: var a = require('./a') 在執行 require(‘./a’) 時,會獲取模塊的接口,若是是第一次調用,會初始化模塊 a,之後再調用時,直接返回模塊 a 的接口 define 只是註冊模塊信息,好比打包以後: define(id, deps, factory) 是註冊了一個模塊到 seajs.cache 中,define 相似: seajs.cache[id] = { id: id, dependencies: deps, factory: factory }

是純註冊信息。

而 require('./a') 時,纔會執行 seajs.cache['a'].factory, 執行後獲得 seajs.cache['a'].exports

擴展:URI與URL的區別

URI:Uniform Resource Identifiers ,統一資源標識符;

URL:Uniform Resource Locators ,統一資源定位符;

URN:Uniform Resource Names,統一資源名稱

URL,URN是URI的子集.

 

5、seajs實戰參考

  該頁面列舉了 SeaJS 中的經常使用實戰過程當中的問題。只要掌握這些方法,就能夠嫺熟地開始對你的網站進行模塊化開發了。

默認狀況下,SeaJS 要求全部文件都是標準的 CMD 模塊,但現實場景下,有大量 jQuery 插件等非 CMD 模塊存在。在 SeaJS 裏,經過如下方式,能夠直接調用非標準模塊。

全站通用的要加載的庫只寫一次,而不想每一個js裏都調用,太繁瑣

 1 //能夠放在在 init.js 裏暴露到全局,這樣,全部在 init.js 以後載入的文件,就均可以直接經過全局變量來拿 $ 等對象。
 2 
 3 seajs.use('init')
 4 
 5 //init.js
 6 define(function(require, exports) {
 7     var $ = jQuery = require('jquery');
 8     
 9     // 暴露到全局
10     window.$ = $;
11 });

 

1. 暴露 jQuery

  jQuery 插件都依賴 jQuery 模塊,爲了加載 jQuery 插件,首先得將 jQuery 模塊暴露出來:

 1 // 配置 jquery 並放入預加載項中
 2 seajs.config({
 3   alias: {
 4     'jquery': 'https://a.alipayobjects.com/static/arale/jquery/1.7.2/jquery.js'
 5   },
 6   preload: ["jquery"]
 7 })
 8 
 9 // 將 jQuery 暴露到全局
10 seajs.modify('jquery', function(require, exports) {
11   window.jQuery = window.$ = exports
12 })

 

2. 修改 jQuery 插件的接口

咱們以 jquery.cookie 插件爲例。

 1 // 配置別名
 2 seajs.config({
 3   alias: {
 4     'cookie': 'https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js'
 5   }
 6 })
 7 
 8 // 將 jQuery Cookie 插件自動包裝成 CMD 接口
 9 seajs.modify('cookie', function(require, exports, module) {
10   module.exports = $.cookie
11 })

 

這樣,在其餘模塊中,就能夠直接調用 cookie 插件了:

 1 a.js:
 2 
 3 define(function(require, exports) {
 4   var cookie = require('cookie')
 5 
 6   cookie('the_cookie')
 7   cookie('the_cookie', 'the_value')
 8 
 9   // ...
10 })

 

seajs裏版本號和時間戳問題

用 seajs 組織項目,上線後,常常須要更新特定文件或全部文件的時間戳,以清空瀏覽器緩存。最簡單的方式是:

 1 //用來維護 jquery 等類庫模塊的版本號
 2 seajs.config({
 3   alias: {
 4     'jquery': 'jquery/1.6.2/jquery',
 5     'backbone': 'backbone/0.5.1/backbone',
 6     'a': 'a.js?20110801',
 7     'b': 'b.js?20110801'
 8   }
 9 });    
10 
11 //利用 map,批量更新時間戳是最方便的
12 seajs.config({
13   'map': [
14     [ /^(.*\.(?:css|js))(.*)$/i, '$1?20110801' ]
15   ]
16 });    

 

條件加載

  第一種:把依賴的模塊都在 define 頭部手工聲明,再也不依賴 SeaJS 的自動解析功能。這個模塊同時依賴 play 和 work 兩個模塊,加載器會把這兩個模塊文件都下載下來。若是須要在 require 模塊以後串行執行代碼,那麼只能用這個方式。

1 define(['play', 'work'], function(require, exports) {
2      //是出去玩,仍是工做?
3     var choice = require(condition() ? 'play' : 'work');
4     //選擇的難度
5     console.log(choice.hard());
6 });

  第二種:使用 require.async 來進行條件加載,從靜態分析的角度來看,require.async適合須要執行動態加載的模塊很大(好比大量 json 數據),不適合都下載下來。可是require.async 方式加載的模塊,不能打包工具找到,天然也不能被打包進上線的 js 中;而前一種方式能夠。

1 define(function(require, exports) {
2     require.async(condition() ? 'play' : 'work', function(choice) {
3         console.log(choice.hard());
4     });
5 });

 

按需加載

不少時候模塊並不須要當即加載,等到須要時再加載,性能更好。

 1 //init.js
 2 $("#J_PicCover").click(function(){
 3     require.async('module/highlight', function(){
 4         $(".buy-info").highlight({color:'#ffe5c4',speed:500,complete:function(){
 5         },iterator:'sinusoidal'});
 6     });
 7 });
 8 
 9 //highlight.js
10 define(function(require, exports) {
11     jQuery.fn.highlight = function(settings) {
12         //…...
13     }
14 });

 

6、seajs快速參考

該頁面列舉了 SeaJS 中的經常使用 API。只要掌握這些方法,就能夠嫺熟地進行模塊化開發。

啓動模塊系統

 1 <script src="http://modules.seajs.org/seajs/1.2.0/sea.js"></script>
 2 <script>
 3       seajs.use('./main');
 4     seajs.use(['./a', './b'], function(a, b) {
 5       a.init();
 6       b.init();
 7     });      
 8 </script>
 9 
10 //callback 參數是可選的。當只啓動加載一個模塊,且不須要 callback 時,能夠用 data-main 屬性來簡化:
11 <script src="http://modules.seajs.org/seajs/1.2.0/sea.js" data-main="./main"></script>
12 
13 /*
14 引入 sea.js 時,能夠把 sea.js 與其餘文件打包在一塊兒,提早打包好,或利用 combo 服務動態打包。
15 不管哪種方式,爲了讓 sea.js 內部能快速獲取到自身路徑,推薦手動加上 id 屬性:
16 加上 seajsnode 值,可讓 sea.js 直接獲取到自身路徑,而不須要經過其餘機制去自動獲取。
17 這對性能和穩定性會有必定提高,推薦默認都加上。
18 */
19 <script src="path/to/sea.js" id="seajsnode"></script>

seajs.config

 1 //seajs.config 能夠疊加,能夠在多處調用,同名 key 覆蓋,不一樣名的 key 疊加。這樣能夠作到:區域配置能夠覆蓋通用配置或能夠說在區域配置中可對 seajs config 再作按需配置而不會影響到通用配置。
 2 seajs.config({
 3 
 4   //alias最經常使用來作版本配置與管理,也能夠用來作命名空間管理。
 5   alias: {
 6     'es5-safe': 'es5-safe/0.9.2/es5-safe',
 7     'json': 'json/1.0.1/json',
 8     'jquery': 'jquery/1.7.2/jquery'
 9   },
10   
11   /*
12   使用 preload 配置項,能夠在普通模塊加載前,提早加載並初始化好指定模塊。
13   注意:preload 中的配置,須要等到 use 時才加載。
14   preload 配置不能放在模塊文件裏面
15   */
16   preload: [
17     Function.prototype.bind ? '' : 'es5-safe',
18     this.JSON ? '' : 'json'
19   ],
20   
21   //值爲 true 時,加載器會使用 console.log 輸出全部錯誤和調試信息。 默認爲 false, 只輸出關鍵信息
22   debug: true,
23   
24   //該配置可將某個文件映射到另外一個。可用於在線調試,很是方便。
25   map: [
26     ['http://example.com/js/app/', 'http://localhost/js/app/']
27   ],
28   
29   /*
30   SeaJS 在解析頂級標識時,會相對 base 路徑來解析。
31   注意:通常請不要配置 base 路徑,保持默認每每最好最方便。
32   base 路徑的默認值,與 sea.js 的訪問路徑相關:
33   若是 sea.js 的訪問路徑是:
34     http://example.com/js/libs/sea.js
35   則 默認base 路徑爲:
36     http://example.com/js/libs/     
37   */ 
38   base: 'http://example.com/path/to/base/',
39   
40   //獲取模塊文件時,<script> 或 <link> 標籤的 charset 屬性。 默認是 utf-8 。
41   charset: 'utf-8'      
42 });

 

seajs.use

 1 /*
 2 模塊加載器
 3 seajs.use 理論上只用於加載啓動,不該該出如今 define 中的模塊代碼裏。在模塊代碼裏須要異步加載其餘模塊時,可使用 require.async 方法。
 4 */
 5 
 6 seajs.use('./a');
 7 
 8 seajs.use('./a', function(a) {
 9   a.doSomething();
10 });
11 
12 seajs.use(['./a', './b'], function(a, b) {
13   a.doSomething();
14   b.doSomething();
15 });
16 
17 //seajs.use 與 dom ready 事件沒有任何關係。
18 //若是某些操做要確保在 dom ready 後執行,須要本身使用 jquery 等類庫來保證
19 seajs.use(['jquery', 'page'], function($, page) {
20   $(function() {
21     page.init()
22   })
23 })

 

define

 1 /*
 2 CMD 模塊定義 define(factory);
 3 define 是全局函數,用來定義模塊。
 4 在開發時,define 僅接收一個 factory 參數。
 5 factory 能夠是一個函數,也能夠是對象、字符串等類型。
 6 factory 爲對象、字符串等非函數類型時,表示模塊的接口就是該對象、字符串等值。
 7 factory 爲函數時,表示模塊的構造方法。執行該方法,能夠獲得模塊向外提供的接口。
 8 */
 9 define(function(require, exports, module) {
10 
11   // The module code goes here
12 
13 });
14 
15 /*
16 模塊代碼須要用 define 回調包起來:id 與 dependencies 參數是能夠省略的
17 id 用來顯式指定模塊 ID。當你的項目上線,全部的模塊都合併到了一個文件中,若是不顯示指定, SeaJS 就無從知道哪一個模塊是哪一個了。在開發的時候,通常用不到它。
18 dependencies 也是如此。它列出了當前模塊所依賴的模塊,在開發的時候是不須要寫明的。 SeaJS 會檢查你的模塊回調函數,找到全部的 require 語句,從而獲得你的模塊的全部依賴。 在真正 require 當前模塊時,會先去請求這個模塊的依賴,加載完畢,再去初始化當前的模塊。
19 */
20 define(id, dependencies, function(require, exports, module) {
21     // module code.
22 });

 

require

 1 /*
 2 require 是一個方法,用來獲取其餘模塊提供的接口。
 3 require 接受 模塊標識 做爲惟一參數
 4 
 5 模塊依賴解析,靠的是三個重要的規則:
 6     不能重命名 require
 7     不能覆蓋 require
 8     require 的參數必須是字符串字面量,不能夠 require(foo()) 或者 require(bar), 也不能夠是 require(should_be_a ? 'a' : 'b')。    參數值必須是字符串直接量,如 require("my-module");
 9     核心緣由是由於在瀏覽器端,文件的讀取是異步的,依賴信息要提早獲取,不能在運行時才肯定。在服務器端,文件讀取是同步的,所以能夠是變量。
10 */
11 define(function(require) {
12   var a = require('./a');
13   a.doSomething();
14 });

 

require.async

 1 /*
 2 require.async(id, callback)
 3 async 方法可用來異步加載模塊,並在加載完成後執行指定回調。
 4 */
 5 define(function(require, exports, module) {
 6   // load one module
 7   require.async('./b', function(b) {
 8     b.doSomething();
 9   });
10 
11   // load multiple modules
12   require.async(['./c', './d'], function(c, d) {
13     // do something
14   });
15 });

require.resolve

1 /*
2 require.resolve(id)
3 使用模塊系統內部的路徑解析機制來解析並返回模塊路徑。該函數不會加載模塊,只返回解析後的絕對路徑。
4 */
5 define(function(require, exports) {
6   console.log(require.resolve('./b')); 
7   // ==> 'http://example.com/js/b.js'
8 });    

 

exports

 1 /*
 2 exports 是一個對象,用來向外提供模塊接口。
 3 exports 僅僅是 module.exports 的一個引用。
 4 在 factory 內部給 exports 從新賦值時,並不會改變 module.exports 的值。
 5 所以給 exports 賦值是無效的,不能用來更改模塊接口,正確的寫法是用 return 或者給 module.exports 賦值。
 6 exports = {}是錯誤的,module.exports ={}纔是正確的寫法。
 7 */
 8 
 9 define(function(require, exports) {
10   // snip...
11   exports.foo = 'bar';
12   exports.doSomething = function() {};
13 });
14 module.exports
15 
16 define(function(require, exports, module) {
17   // snip...
18   module.exports = {
19     name: 'a',
20     doSomething: function() {};
21   };
22 });

 

module

 1 *
 2 module 是一個對象,上面存儲了與當前模塊相關聯的一些屬性和方法。
 3 */
 4 define(function(require, exports, module) {
 5 
 6     //module.id 模塊標識。require(module.id) 必然返回此模塊的 exports 。
 7    console.log(require(module.id) === exports); // true
 8    
 9    //module.uri根據模塊系統的路徑解析規則獲得的模塊絕對路徑。
10    console.log(module.uri); // http://example.com/path/to/this/file.js
11    
12    //module.dependencies dependencies 是一個數組,表示當前模塊的依賴列表。
13    
14    /*
15    module.exports 當前模塊對外提供的接口。
16    module.exports 的賦值須要同步執行,不能放在回調函數裏
17    */
18 });

 

以上接口是最經常使用的,要牢記於心。

可寫成以下

 1 seajs.config({
 2   alias: {
 3     'jquery': 'http://modules.seajs.org/jquery/1.7.2/jquery.js'
 4   }
 5 });
 6 
 7 define('hi', function(require, exports) {
 8     exports.sayHi = function() {
 9         alert('hi')
10     } 
11 })
12 
13 seajs.use(['jquery', 'hi'], function($, h) {
14     $('#beautiful-sea').click(h.sayHi)
15 });

模塊化後的js寫法

 1 define(function(require, exports, module) = {
 2  
 3     //原jquery.js代碼...
 4  
 5     module.exports = $.noConflict(true);
 6 });
 7  
 8 //init.js
 9 define(function(require, exports, module) = {
10     var $ = require('jquery');
11     var m1 = require('module1');
12      
13     exports.initPage = function() {
14         $('.content').html(m1.run());    
15     }
16 });
17  
18 //module1.js
19 define(function(require, exports, module) = {
20     var $ = require('jquery');
21     var m2 = require('module2');
22     var m3 = require('module3');
23      
24     exports.run = function() {
25         return $.merge(['module1'], $.merge(m2.run(), m3.run()));    
26     }
27 });
28  
29 //module2.js
30 define(function(require, exports, module) = {
31     exports.run = function() {
32         return ['module2'];
33     }
34 });
35  
36 //module3.js
37 define(function(require, exports, module) = {
38     var $ = require('jquery');
39     var m4 = require('module4');
40      
41     exports.run = function() {
42         return $.merge(['module3'], m4.run());    
43     }
44 });
45  
46 //module4.js
47 define(function(require, exports, module) = {
48     exports.run = function() {
49         return ['module4'];
50     }
51 });

 

實際使用中

  在工程內使用seajs,之前引用的插件、模塊也都要用define的語法從新進行封裝,比較麻煩,老代碼能夠不修改,繼續使用就好。但強烈創建花點時間都修改爲 CMD 模塊,這樣對之後的維護,以及頁面性能頗有好處。否則之後修改起來估計會更麻煩。

其實能夠混用的,好比:

1 <script src="jquery.js"></script>
2 <script src="underscore.js"></script>
3 <script src="backbone.js"></script>
4 
5 <script src="sea.js"></script>

  這樣,經常使用的 jquery 等類庫,依舊是傳統的用法,用全局變量引用就好,經過同步引入的方式,也不會有依賴順序問題。 本身的代碼,都按照 CMD 規範寫成模塊的形式。

  其實上面的方式挺好的,特別對於要兼容老代碼的狀況的。 推薦仍是都完全模塊化,看起來要多寫一些 require,但值得,由於這樣可讓每一個模塊自身的信息完整,從而減小對 環境的依賴,對後續的可維護性很好益處。

 

seajs官方api

第三方庫

SeaJS 提供了一個相似於npm的管理工具,裏面有他們改造好的第三方庫,你能夠在這裏找找是否有適合的:

seajs blog 等文檔

初級入門

中級使用

高級探索

 

http://www.heiniuhaha.com/seajs/2012/08/13/seajs-cheet-sheet/ 轉

 

7、實例

 1 // 頁面調用
 2 <script src="js/sea.js"></script>
 3 <script>
 4     seajs.use('init', function(a){
 5 
 6         // a是init模塊的外部接口,等init加載完就會將
 7         a.init();
 8 
 9     });
10 </script>
11 
12 
13 // init.js
14 // 基本配置
15 seajs.config({
16     alias: {
17         'jquery': 'jquery.min.js',
18         'transition': 'animate'
19     }
20 });
21 
22 define(function(require, exports, module){
23 
24     var an = require("transition");
25     require("jquery");      // 注意加載jquery只須要加載,不能賦值給一個變量來調取
26 
27     function init(){
28         alert("aa");
29     }
30 
31     $("#moveBtn").click(function(){
32         an.moveBox($(".box"));
33     })
34 
35     exports.init = init;
36 })
37 
38 
39 // animate.js
40 define(function(require, exports, module){
41 
42     // 模塊外部接口
43     exports.moveBox = function(boxId){
44         boxId.stop().animate({left: "1000px"}, 5000);
45     }
46 
47     // 模塊接口,也將暴露給全局
48     window.moveBox = exports.moveBox = function(boxId){
49         boxId.stop().animate({left: "1000px"}, 5000);
50     }
51 
52 })
相關文章
相關標籤/搜索