requireJs筆記,requirejs

來源:互聯網
上載者:User

requireJs筆記,requirejs

官方網址:http://www.requirejs.org/

中文版翻譯:http://makingmobile.org/docs/tools/requirejs-api-zh/

外掛程式作用:對於JS模組檔案進行管理,動態載入,項目完成時合并壓縮模組。

 

一、基本用法:

1、外鏈檔案,data-main中為外鏈的檔案名稱,無需加尾碼:

<script data-main="js/main" src="require.js"></script>

 

2、頁面直接寫入代碼(可將data-main設為require.config設定檔):

require.config({      baseUrl:'./js',    paths: {          "a": "other/a",          "b": "other/b",          "c": "some/c",          "d": "some/d"    },    waitSeconds: 150});//依賴載入(外層先載入)require(["a","c","d","b"], function() {  a();c();d();b();});

二、文法摘要(詳細文法參見官方API)

1、引用外掛程式內函數

Test.js:

define({test:function(msg) {        alert("test" + msg);    },userName: "111"});

Requirjs引用:

require(["test"], function (a) {  //a按順序對應載入的檔案    a.test("asdf");});

2、require函數外部調用內部定義的函數,需等require內檔案都載入完成了才有效

3、檔案依賴載入(當前外掛程式依賴jquery,需等jquery載入完成後才會執行)

define(['jquery'],function($){    var returnVar = {        userName: "111",        aa: function(){}    }    return returnVar;});

4、外掛程式引用外部函數

外部函數:

function callE(msg){alert('e'+msg)}function callF(msg){alert('f'+msg)}

Require配置:

require.config({    baseUrl:'./js',    paths: {          "e": "other/e",          "f": "other/f"    },config:{  //外部函數賦值'e': {   //e指對應載入的模組名size: 'eee',cal:callE},'f':{size: 'fff',cal:callF}},    waitSeconds: 150})

外掛程式引用:

define(function(require, exports, module){function aa(){module.config().cal('123e');}var m={aa:aa}return m;})

5、jsonp服務,JSONP的callback參數為"callback",因此"callback=define"告訴API將JSON響應包裹到一個"define()"中。

require(["http://example.com/api/data.json?callback=define"],    function (data) {        //data將作為此條JSONP data調用的API響應        console.log(data);    });

JSONP的這種用法應僅限於應用的初始化中。一旦JSONP服務逾時,其他通過define()定義了的模組也可能得不得執行,錯誤處理不是十分健壯。

6、shim: 為那些沒有使用define()來聲明依賴關係、設定模組的"瀏覽器全域變數注入"型指令碼做依賴和匯出配置。

requirejs.config({    shim: {        'jquery.colorize': {            deps: ['jquery'],            exports: 'jQuery.fn.colorize'        },        'jquery.scroll': {            deps: ['jquery'],            exports: 'jQuery.fn.scroll'        },        'backbone.layoutmanager': {            deps: ['backbone']            exports: 'Backbone.LayoutManager'        }    }});

7、paths備錯配置

requirejs.config({    //為了在IE中正確檢錯,強制define/shim匯出檢測    enforceDefine: true,    paths: {        jquery: [           'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min',            //若CDN載入錯,則從如下位置重試載入            'lib/jquery'        ]    }});

8、DOM Ready

在DOM載入完成後執行requeire內代碼,domReady外掛程式需另外載入。

require(['domReady!'], function (doc) {    //本函數會在DOM ready時調用。    //注意'domReady!'的值為當前的document});

9、錯誤捕獲

requirejs.onError = function (err) {    console.log(err.requireType);    if (err.requireType === 'timeout') {        console.log('modules: ' + err.requireModules);    }    throw err;};

三、r.js模組合并壓縮

需在目錄中放置r.js,同時有一個合并規則設定檔

例如build.js:

({    appDir: './',    baseUrl: './js',    dir: './dist',    modules: [        {            name: 'config'         //頁面中data-main引入檔案exclude:['other/b']    //不合并壓縮的檔案        },{            name: 'config2'        },{            name: 'main'        }    ],    fileExclusionRegExp: /^(r|build)\.js$/,    optimizeCss: 'standard',    removeCombined: true,    paths: {a:'empty:',     //empty:指不被壓縮合并,單獨請求b:'other/b',c:'some/c',d:'some/d',e:'other/e',f:'other/f'    }})

r.js依賴於nodejs環境,使用方法:進入檔案所在目錄,運行node r.js -o build.js

四、項目執行個體

項目背景:VC內嵌網頁項目,需與VC進行簡單資料互動

代碼設計:

1、  獨立檔案設定檔路徑,在require.js之前獨立引用載入

Config.js:

//將配置作為全域變數"require"在require.js載入之前進行定義,它會被自動應用。下面的樣本定義的依賴會在require.js,一旦定義了require()之後即被載入var require={      baseUrl:'./js',    paths: {          "a": "other/a",          "b": "other/b",          "c": "some/c",          "d": "some/d"     },    waitSeconds: 150}

2、  頁面引入檔案(模組檔案使用代碼)

<scriptdata-main="test6" src="require.js"></script>

3、  按功能劃分模組及目錄

4、  提取介面。

把需要引用的VC定義的函數,在config.js裡通過config.cal()重新賦值。

提供給VC調用的函數(大部分為事件執行之後的回調),在config.js定義一個初始化對象,然後在各模組裡進行相應賦值,如初始化對象:
Var vcCallback={refreshList:function(){},   //重新整理列表資料refreshUserInfo:function(){}   //重新整理使用者資料}

在require()代碼裡對其重寫,如:vcCallback.refreshList=createView;




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.