標籤:style blog http color os strong
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/