require.js 基礎使用方法記錄

來源:互聯網
上載者:User

標籤:使用   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 基礎使用方法記錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.