欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-05-16 09:39:20|栏目:JavaScript代码|点击:

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;
});

文件的加载顺序

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,一切都很自然。

上一篇:浅析微信小程序自定义日历组件及flex布局最后一行对齐问题

栏    目:JavaScript代码

下一篇:基于JS实现简单的样式切换效果代码

本文标题:JavaScript的模块化开发框架Sea.js上手指南

本文地址:http://www.codeinn.net/misctech/122872.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有