Sea.js所有源碼都存放在 GitHub 上:https://github.com/seajs/examples,目錄結構為:
examples/ |-- sea-modules 存放 seajs、jquery 等文件,這也是模塊的部署目錄 |-- static 存放各個項目的 js、css 文件 | |-- hello | |-- lucky | `-- todo `-- app 存放 html 等文件 |-- hello.html |-- lucky.html `-- todo.html
引入seajs主文件
<script src="js/sea.js"></script><script type="text/javascript"> // seajs配置項 seajs.config({ //設置基本的JS路徑(引用外部文件的根目錄) base:"./js", //設置別名(方便后面引用使用) alias:{ "jQuery":"jquery.js" }, //路徑配置(跨目錄調用或者目錄比較深時使用) paths: { 'jQuery': 'http://libs.baidu.com/jquery/2.0.0/' }, //設置文件編碼 charset:"utf-8", //預加載文件 preload:['jQuery'] }); // 引用主入口文件 seajs.use(['main','jQuery'],function(e,$){ //回調函數 alert("全部加載完成"); });</script>seajs主入口文件(main)
define(function(require, exports, module) { // 主入口文件引入其他文件依賴 //var testReQ = require('index'); var testReQ = require.async('index',function(){ //異步加載回調 alert("我是異步加載的index的回調函數"); }); // 運行index釋放的接口方法 // testReQ.testInit(); // 運行index釋放的接口方法(module) testReQ.textFun();});seajs依賴文件(index)
define(function(require, exports, module) { // 對外釋放接口 exports.testInit = function(){ alert("我是一個接口"); }; // 如果需要釋放大量接口,可以使用module var testObj = { name:"qiangck", sex:"man", textFun:function(){ alert("我是一個使用module.exports的對象方法"); } } // module.exports接收obj對象 module.exports = testObj;});文件的加載順序

下面我們從 hello.html 入手,來瞧瞧使用 Sea.js 如何組織代碼。
在頁面中加載模塊
在 hello.html 頁尾,通過 script 引入 sea.js 后,有一段配置代碼:
// seajs 的簡單配置seajs.config({ base: "../sea-modules/", alias: { "jquery": "jquery/jquery/1.10.1/jquery.js" }})// 加載入口模塊seajs.use("../static/hello/src/main")sea.js 在下載完成后,會自動加載入口模塊。頁面中的代碼就這么簡單。
模塊代碼
這個小游戲有兩個模塊 spinning.js 和 main.js,遵循統一的寫法:
// 所有模塊都通過 define 來定義define(function(require, exports, module) { // 通過 require 引入依賴 var $ = require('jquery'); var Spinning = require('./spinning'); // 通過 exports 對外提供接口 exports.doSomething = ... // 或者通過 module.exports 提供整個接口 module.exports = ...});上面就是 Sea.js 推薦的 CMD 模塊書寫格式。如果你有使用過 Node.js,一切都很自然。
新聞熱點
疑難解答