標籤:style blog http color strong 檔案
一、Sea.js和Grunt構建工具
好處:
sea.js按需載入,用到哪些模組會載入哪些模組,節省http請求
Grunt構建工具:可以對檔案進行壓縮和合并
二、API 快速參考一、seajs.config
用來對 Sea.js 進行配置。
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 });
二、seajs.use
用來在頁面中載入一個或多個模組。
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 });
三、define
用來定義模組。Sea.js 推崇一個模組一個檔案,遵循統一的寫法:
1 define(function(require, exports, module) {2 3 // 模組代碼4 5 });
require, exports 和 module 三個參數可酌情省略,具體用法如下。
四、require
require 用來擷取指定模組的介面。
1 define(function(require) {2 3 // 擷取模組 a 的介面4 var a = require(‘./a‘);5 6 // 調用模組 a 的方法7 a.doSomething();8 });
注意,require 只接受字串直接量作為參數
五、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 });
六、exports
用來在模組內部對外提供介面。
1 define(function(require, exports) {2 3 // 對外提供 foo 屬性4 exports.foo = ‘bar‘;5 6 // 對外提供 doSomething 方法7 exports.doSomething = function() {};8 9 });
七、module.exports
與 exports 類似,用來在模組內部對外提供介面。
1 define(function(require, exports, module) {2 3 // 對外提供介面4 module.exports = {5 name: ‘a‘,6 doSomething: function() {};7 };8 9 });
module.exports 與 exports 的區別
以上 7 個介面是最常用的,要牢記於心。