模組化開發之seajs
阿新 • • 發佈:2019-01-10
1、seajs的下載及配置
下載:由於seajs官網打不開,可百度搜索seajs下載,進行下載
配置:將下載後的sea.js檔案新增到自己的網站目錄下,如圖:
2、seajs的引入
seajs的引入方式跟其他js檔案的引入方式一樣,通過<script>標籤的src引入,如下圖:
3、seajs的使用
(1)定義模組
seaJs 模組與模組之間可以存在依賴關係。
模組的編寫方式如下:
module1.js檔案
模組中引入模組,從下面的程式碼可以看出, module2的程式碼依賴module1.js中的程式碼 module2.js檔案define(function( require, exports, module ){ function show(){ alert('module1-show'); } //通過exports把show方法 提供給外部使用 exports.show = show; });
(2)引用模組 編寫方式:seajs.use('模組的路徑', function(ex){}); 例如,在index.html裡引用 index.html檔案define(function( require, exports, module ){ //require("./module1.js"):引入第一個模組 相當於exports var show2 = require("./module1.js").show; //引入需要的模組(即相應js檔案) show2();//呼叫 //下面是module2.js自己的程式碼 與呼叫module1無關。 function show(){ alert('module2-show'); } //通過exports把show方法 提供給外部使用 exports.show = show; });