SeaJs:
web浏览器端的模块加载器,常常看到杂乱的js引入,这个组件模块化的管理我们的js文件。哇,整个世界都清爽了......生活更加的美好了!
实例代码:
define(function(require, exports, module) { var $ = require('jquery'); exports.sayHello = function() { $('#hello').toggle('slow'); };});
将上面的代码保存为 hello.js
,然后就可以通过 SeaJS 来加载使用了:
seajs.config({ alias: { 'jquery': 'http://modules.seajs.org/jquery/1.7.2/jquery.js' }});seajs.use(['./hello', 'jquery'], function(hello, $) { $('#beautiful-sea').click(hello.sayHello);});
hello.js文件被seajs解析之后,应该变成一个javascript中的对象了。详见:
模块系统
seajs中一切皆是模块,通过模块来组成我们系统。模块遵循一定的书写规则( 这里可以查看cmd规则的API),彼此引用,协同工作,这就是seajs核心思想。
CMD(Common Module Definition)
1、cmd中一个javascript就是一个模块,代码书写格式:
define(factory)
功能定义模块 factory 模块:对象,字符串,json等;函数,当前模块的构造函数,包含三个参数:require,exports,module
1 define(function(require, exports, module) {2 3 /**require(id)** : a method to call to other module by module ID; Example: var a = require('./a');4 The same function is require.async(id,callback)*/5 /**exports**: is an object that supply a interface to other's module*/6 /**module**: is an object that record information of current module.* /7 });
以上就是CMD常用API(define,require,require.async,export,module).
模块标识
2、模块标识的书写规则。可以详见:
3、模块标示的设计原则:
a. 简化引用,关注度分离,相对性加强。
b. 尽量与浏览器的规则一致,方便解析。
模块加载器(module loader)
seaJs作为模块加载器,需要实现两个功能:
4、对模块的实现规则进行定义,模块系统的基础(上面以介绍)。
5、模块加载器的启动与运行。
//seaJs is simple for running.
小结:
seaJs实现思想就是简单,简洁。虽然还有一些配置,插件之类的没有介绍,但是都很简单,在自己的需要的时候,查询一下其官方网站就可以了。