Welcome 微信登录

首页 / 脚本样式 / JavaScript / JavaScript的模块化开发框架Sea.js上手指南

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("我是一个接口");};// 如果需要释放大量接口,可以使用modulevar testObj = {name:"qiangck",sex:"man",textFun:function(){alert("我是一个使用module.exports的对象方法");}}// module.exports接收obj对象module.exports = testObj;});
文件的加载顺序

2016512154937332.png (726×233)

下面我们从 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,一切都很自然。