源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JavaScript的模块化开发框架Sea.js上手指南

  • 时间:2021-06-29 07:21 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要: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

[b]引入seajs主文件[/b]
<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>
[b]seajs主入口文件(main)[/b]
define(function(require, exports, module) {
  // 主入口文件引入其他文件依赖
  //var testReQ = require('index');
   var testReQ = require.async('index',function(){
      //异步加载回调
      alert("我是异步加载的index的回调函数");
   });
  // 运行index释放的接口方法
  // testReQ.testInit();

  // 运行index释放的接口方法(module)
  testReQ.textFun();
});

[b]seajs依赖文件(index)[/b]
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;
});
[b]文件的加载顺序 [/b] [img]http://files.jb51.net/file_images/article/201605/2016512154937332.png?2016412155037[/img] 下面我们从 hello.html 入手,来瞧瞧使用 Sea.js 如何组织代码。 [b]在页面中加载模块[/b] 在 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 在下载完成后,会自动加载入口模块。页面中的代码就这么简单。 [b]模块代码[/b] 这个小游戏有两个模块 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,一切都很自然。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部