標籤:使用 html .config pat tps 特定 export efi 結構
require.js作為javsscript的一種模組化編程規範,非同步載入模組,主要應用於瀏覽器端,非同步載入js檔案,讓瀏覽器不會因為在載入js檔案而失去響應。
一、開始
目錄結構:
首先要載入require.js
<!-- ***.html--><script data-main="js/app.js" src="js/require.js" defer></script>
app.js即是入口檔案,我們在裡面載入math.js
//app.js
require([‘app/math‘],function(math){ console.log(‘1 + 3 = ‘,math.add(1,3));})
math.js的編寫要符合AMD規範
// math.jsdefine(function(){ var add = function(a,b){ return a+b; } return { add:add }})
這時候運行就可以列印相應的結果
二、載入不符合AMD規範的js檔案
require.js為我們提供了一個shim方法,協助我們載入一些不符合AMD規範的js檔案
首先我們隨便在People.js裡面寫點內容:
//People.jsvar People = function(name){ this.name = name; this.sayName = function(){ console.log(`my name is ${this.name}`); };};
改寫app.js
//app.jsrequire.config({ shim:{ ‘app/People‘:{ deps:[], // 這裡聲明依賴檔案 exports:‘People‘ // 輸出方法 } }});require([‘app/math‘,‘app/People‘],function(math,People){ console.log(‘1 + 3 = ‘,math.add(1,3)); var jack = new People(‘jack‘); jack.sayName();})
運行,正確輸出:
三、baseUrl和paths
require提供一些協助我們定位檔案的方法
在app.js中添加baseUrl:
// app.jsrequire.config({ baseUrl:‘js/app‘, //相對於html目錄定位 shim:{ People:{ deps:[], // 這裡聲明依賴檔案 exports:‘People‘ // 輸出方法 } }});require([‘math‘,‘People‘],function(math,People){ console.log(‘1 + 3 = ‘,math.add(1,3)); var jack = new People(‘jack‘); jack.sayName();})
同樣可以輸出相應的結果:
我們還可以為特定的檔案指定paths,比如我們要引入jquery:
require.config({ baseUrl:‘js/app‘, //相對於html目錄定位 paths:{ jquery:‘../lib/jquery‘ // 相對於baseUrl定位 }, shim:{ People:{ deps:[], // 這裡聲明依賴檔案 exports:‘People‘ // 輸出方法 } }});require([‘math‘,‘People‘,‘jquery‘],function(math,People,$){ $(function(){ console.log(‘1 + 3 = ‘,math.add(1,3)); var jack = new People(‘jack‘); jack.sayName(); })})
同樣輸出了一樣的結果:
require.js 基礎使用方法記錄