首页 > 网站 > WEB开发 > 正文

模块化JS编程 seajs简单例子

2024-04-27 14:21:20
字体:
来源:转载
供稿:网友

模块化JS编程 seajs简单例子

1.引入sea.js

test.html

 1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>My Frist SeaJs</title> 6 </head> 7 <body> 8 <div id="container"> 9  10 </div>11 12 <script src="../sea-modules/seajs/seajs/2.2.0/sea.js"></script>13 <script>14 15   // Set configuration16     seajs.config({17          alias: {18              "jquery": "../script/jquery-1.11.1"19         }20     });21 22   seajs.use("../script/mysea.js");23 </script>24 25 </body>26 </html>

2.定义mysea.js

mysea.js

1 define(function (require, exports, module) {      //获得依赖2     var mysea2 = require('../script/mysea2');3     mysea2.show();4 });

2.定义mysea2.js

mysea2.js

1 define(function (require, exports, module) {      //暴露show接口2     exports.show = function() {3         alert('mysea2');4     };5 });

输出结果:

模块化编程的目的很明显,我们不在像以前那样function(),function()的编写代码.我们可以很自由的组织代码,可避免一些代码冲突.

这里有个小问题,demo 引用的是jquery-1.11.1.由于jquery遵循是AMD规范. 在seajs官网的例子运行是没有问题的,因为作了修改(seajs是CMD规范).

所以jquery-1.11.1也做了修改,否则依赖的jquery会找不到的.

jquery-1.11原本的定义

1 if (typeof define === "function" && define.amd) {2         define("jquery", [], function () {3         return jQuery;4    });5 }

修改如下

1 if (typeof define === "function") {      //合理的路径2     define("../script/jquery-1.11.1", [], function () { return jQuery; });3 }

关于规范

AMD规范:https://github.com/amdjs/amdjs-api/wiki/AMD

seajs模块定义规范:https://github.com/seajs/seajs/issues/242

下载seajshttps://github.com/seajs/seajs/releases官网http://seajs.org/docs/
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表