Foreword
SeaJS is a JavaScript module loading framework that follows the CommonJS specification and can realize modular development and loading mechanism of JavaScript. Using SeaJS can improve the readability and clarity of JavaScript code, solve common problems such as dependency confusion and code entanglement in current JavaScript programming, and facilitate code writing and maintenance.
SeaJS itself is developed following the KISS (Keep it Simple, Stupid) concept, and subsequent version updates are also clamoring to move in this direction.
How to use SeaJS
I won’t go into details here about downloading and installation. If you don’t understand, please check the official website.
Basic Development Principles
•Everything is a module: The concept of modules in SeaJS is somewhat similar to classes in object-oriented - modules can have data and methods, data and methods can be defined as public or private, and public data and methods can be called by other modules.
•Each module should be defined in a separate js file, that is, one corresponding to one module.
Definition and writing of modules
Module definition function define
Use the define function in SeaJS to define a module. define can receive three parameters:
/** * Defines a module. * @param {string=} id The module id. * @param {Array.|string=} deps The module dependencies. * @param {function()|Object} factory The module factory function. */ fn.define = function(id, deps, factory) { //code of function… }
The parameters that define can receive are module ID, dependent module array and factory function.
•If there is only one parameter, assign it to factory
•If there are two parameters, the second one is assigned to factory, the first one is assigned to deps if it is an array, otherwise it is assigned to id
•If there are three parameters, assign values separately
However, almost all places where define is used, including the SeaJS official website example, only pass a factory function into it, similar to the following code:
define(function(require,exports,module){ //code of the module })
Personally, it is recommended to follow the standard of SeaJS official example and define the module with a parameter define. So what will happen to ids and deps?
id is the identification string of a module. When define has only one parameter, id will be assigned the absolute path of this js file by default. If define is used to define a module in the a.js file under example.com, the ID of this module will be assigned the value http://example.com/a.js. It is recommended not to pass it in if there is no special need. id. Generally, deps does not need to be passed in. The modules that need to be used can be loaded with require.
Factory function factory analysis
Factory function is the main body and focus of the module. Its three parameters are:
•require: module loading function, used to record dependent modules
•Exports: Interface point, data or methods defined on it will be exposed to external calls
•Module: Module metadata
These three parameters can be displayed and specified as needed.
Module is an object that stores the meta-information of the module, as follows:
•module.id: module ID
•module.dependencies: an array that stores a list of IDs of all modules that this module depends on.
•module.exports: points to the same object as exports
Three modes of writing modules
The first is the exports-based mode:
define(function(require,exports,module){ var a=require('a'); var b=require('b'); //引入模块 var data1=1; //私有数据 var fun1=function(){//私有方法 return a.run(data1); } exports.data2=2; //公有数据 exports.fun2=function(){ return 'hello'; } })
The above is a relatively "authentic" module definition mode. In addition to attaching public data and methods to exports, you can also directly return an object representation module. For example, the following code has the same function as the above code:
define(function(require){ var a=require('a'); var b=require('b'); //引入模块 var data1=1; var fun1=function(){ return a.run(data1); } return{ data2:2, fun2:function(){ return 'hello'; } } })
If the module definition has no other code and only returns an object, it can also be simplified as follows:
define({ data2:2, fun2:function(){ return 'hello'; } })
The third way of writing is very suitable for modules that define pure JSON data.
Depending on different application scenarios, SeaJS provides three APIs for loading modules, namely: seajs.use, require and require.async.
seajs.use
seajs.use is mainly used to load entry modules. The entry module is equivalent to the main function of C language and is also the root of the entire module dependency tree. seajs.use
The usage of is as follows:
//第一模式 seajs.use('./a'); //回调模式 seajs.use('./a',function(a){ a.run(); }) //多模块模式 seajs.use(['./a','./b'],function(a,b){ a.run(); b.run(); })
The usage of multi-modules is similar to the module loading method in KISSY. It’s no wonder it was written by one person!
Generally seajs.use is only used to load the entry module on the page. SeaJS will parse all dependent modules along the entry module and load them. If there is only one entry module, you can also omit seajs.use by adding the "data-main" attribute to the script tag that introduces seajs. For example, it is written as follows:
<!DOCTYPE HTML> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>TinyApp</title> </head> <body> <p class="content"></p> <script src="./sea.js" data-main="./init"></script> </body> </html> require
require is the main module loading method of seajs. When other modules are needed in a module, require is generally used to load:
var m=require('./a'); require.async
上文说过seajs会在html页面打开时通过静态分析一次性记载所有需要的js文件,如果想要某个js文件在用时才加载,可以使用require.async。
这样只有在用到这个模块时,对应的js文件才会被下载,也就实现了JavaScript代码的按需加载。
SeaJS的全局配置
seajs提供了一个seaj.configd的方法可以设置全局配置,接收一个表示全局配置的配置对象,具体方法如下:
seajs.config({ base:'path', alias:{ 'app':'path/app/' }, charset:'utf-8', timeout:20000, debug:false })
其中,
•base表示基址路径
•alias可以对较长的常用路径设置缩写
•charset表示下载js时script标签的charset属性。
•timeout表示下载文件的最大时长,以毫秒为单位。
Seajs如何与现有的JS库配合使用
要将现有的JS库与seajs一起使用,只需根据seajs的模块定义规则对现有库进行一个封装。例如,下面是对jQuery的封装方法:
define(function(){ /* 此处为jquery源码 */ })
一个完整的例子:
上文说了那么多,知识点比较分散,所以最后我打算用一个完整的SeaJS例子把这些知识点串起来,方便朋友们归纳回顾。这个例子包含如下文件:
•index.html 主页面
•sea.js
•jquery.js
•init.js init模块,入口模块,依赖data、jquery、style三个模块,又主页面载入
•data.js data模块,纯json数据模块
•style.css css样式表
html: <!DOCTYPE HTML> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="content"> <p class="author"></p> <p class="blog"><a href="#">Blog</a></p> </div> <script src="sea.js"></script> <script> seajs.use('init'); </script> </body> </html> javascript: //init.js define(function(require, exports, module) { var $ = require('./jquery'); var data = require('./data'); var css = require('./style.css'); $('.author').html(data.author); $('.blog').attr('href', data.blog); }); //data.js define({ author: 'ZhangYang', blog: 'http://blog.codinglabs.org' }); css: .author{color:red;font-size:10pt;} .blog{font-size:10pt;}
请注意:
1.请讲jquery.js源码文件包含在seajs模块加载代码中;
2.在Sea.js < 2.3.0版本之前是可以加载css文件的,新版本中此功能移除,为了兼容考虑,加载css功能将作为一个插件存在。
使用方法
•可以在sea.js标签后引入这个插件使用
•也可以将插件代码混入sea.js当中
•和seajs-style的区别 •seajs-css是使 Sea.js 能够加载一个css文件,和link标签一样
•seajs-style是指提供一个seajs.importStyle方法用于加载一段 css 字符串
以上内容是小编给大家分享的JavaScript模块化开发之SeaJS,希望对大家学习javascript模块化开发有所帮助,谢谢大家一直以来对脚本之家网站的支持。!