在ASP.NET MVC項目中使用RequireJS庫的用法樣本,mvcrequirejs

來源:互聯網
上載者:User

在ASP.NET MVC項目中使用RequireJS庫的用法樣本,mvcrequirejs

RequireJS 是一個前端模組化開發的流行工具,本身是一個Javascript的庫檔案,即require.js 。
RequireJs的主要功能:

(1)實現js檔案的非同步載入,避免網頁失去響應;

(2)管理模組之間的依賴性,便於代碼的編寫和維護。

前端模組化開發現在有好多的工具,大體上分為兩類,一類是像dojo之類的高大全,dojo v1.8之後已經內建了模組化開發組件;另一類是像require.js,sea.js 這種專心做模組化開發的工具。

從模組化劃分的規則來區分,主要分為AMD、CMD兩類,dojo、require.js 遵從前者,而sea.js 依循CMD規範。

require在單頁面應用中能夠如魚得水,然而對於傳統的多頁面應用,使用require多少會有些困惑和不方便。

本文講解如何在ASP.NET MVC的結構中應用require,並且給出了壓縮指令碼,實現半自動化壓縮。

將js代碼分離
一般而言ASP.NET MVC的一個路由對應一個視圖,視圖的檔案結構可能如下:


Views |--Shared |--_layout.cshtml |--Home |--Index.cshtml |--Blog |--Create.cshtml |--Edit.cshtml |--Detail.cshtml |--Index.cshtml

這裡假設_layout.cshtml是所有頁面共用的。一般情況下,我們會在_layout中引用公用的js類庫,比如jQuery,bootstrap等,這樣的話其他的頁面就不需要對這些類庫再引用一遍,提高了編碼的效率。然而,不同的頁面終究會依賴不同的js,尤其是實現頁面本身功能的自訂的js,這樣我們不得不在其他頁面中再引用特殊的js,甚至將js直接寫在頁面中,例如下面的代碼經常會出現在View中:

<script type="text/javascript"> $(function(){...});</script>

這樣會導致頁面比較混亂,而且頁面<script>標籤中代碼不能被瀏覽器緩衝,增加了頁面代碼的長度。更為重要的缺陷是,諸如jQuery之類的類庫會在載入到頁面後執行匿名函數,這需要一些時間,而如果有些頁面根本不需要jQuery的話,只要頁面把_layout作為布局頁面,那麼jQuery的初始化代碼將不可避免的執行,這是一種浪費。事實上,javascript的模組化載入的思想就是為瞭解決這些問題的。

接下來我們來用require規劃我們的js,構建諸如下面結構的js目錄


js|--app |--home.index.js |--blog.create.js |--blog.edit.js |--blog.detail.js |--blog.index.js|--jquery.js|--bootstrap.js|--underscore.js|--jquery.ui.js|--jquery.customplugin.js|--config.js|--require.js

把公用的類庫層級的js模組直接放在js目錄下,而把頁面層級的js放在一個app的子目錄下。注意,在app中,每個頁面一個js檔案,這意味著我們需要把頁面各自的js提取出來,雖然這樣增加了結構複雜度,但是避免了在頁面中隨手寫<script>標籤的陋習。另外,在js目錄下的公用庫,除了第三方的庫,還包括自己開發的庫,還有一個叫config.js的檔案,這個檔案很關鍵,稍後會說到。

然後,我們可以刪除_layout中所有的js引用,並使用@RenderSection的命令要求子頁面提供js引用,_layout.cshtml:

<head>...@RenderSection("require_js_module", false)...</head>

這樣對js的需求就下放到每個view頁面中了,根據require的用法,我們需要在各個子View中引用require.js,並指定主模組,而這些主模組就是上面app目錄下的一個個js

@section require_js_module{ <script src="@Url.Content("~/js/require.js")" data-main="@Url.Content("~/js/app/home.index.js")" ></script>}

所有的js代碼都將寫到app下的js中,這樣規範了js,使得頁面更乾淨,更為重要的是這些js還可以經過壓縮,以及被瀏覽器緩衝等,進一步提高執行效率

公用的config
我們知道主模組除了使用require方法外,經常需要通過require.config來配置其他模組的路徑,甚至需要shim,例如下面的代碼經常會出現在主模組的開頭:

require.config({ paths: { "jquery": "lib/jquery.min", "underscore": "lib/underscore.min", "backbone": "lib/backbone.min" }, shim: { 'underscore':{  exports: '_' }, 'backbone': {  deps: ['underscore', 'jquery'],  exports: 'Backbone' } }});
對於單頁面應用來說,主模組往往只有一個,所以上面的代碼寫一遍也就OK了。但是,在多頁面的情況下,主模組有多個,每個主模組都要包含這樣的代碼,豈不是很不科學?於是,希望有一個統一配置的地方,但是應該如何來寫呢?我們想到,將這些配置作為一個模組config.js,讓其他的主模組對這個模組產生依賴就可以了,例如下面的config.js:
requirejs.config({ paths: { "jquery": "/js/jquery.min", "bootstrap": "/js/bootstrap" }, shim: { 'bootstrap': {  deps: ['jquery'],  exports: "jQuery.fn.popover" } }});

config.js的寫法沒有什麼特別的,接下來只要在home.index.js中引用

require(['../config','jquery', 'bootstrap'], function () { //main module code here});

不過這樣寫還是不對的,因為,被主模組依賴的模組(這裡的config,jquery,bootstrap),在載入的時候,載入順序是不確定的,但是又需要config模組在其他模組之前載入,怎麼辦呢?一個折衷的方案是修改home.index.js,成為如下代碼:

require(['../config'], function () { require(['home.index2']);}), define("home.index2", ['jquery', 'bootstrap'], function () { //main module code here})

使用一個命名的模組home.index2作為過渡,在主模組中手動require,這樣可以保證config在主模組執行之前載入,也就使得home.index2在載入的時候已經載入了config了。

壓縮
require提供一個壓縮公用程式,用於壓縮和合并js,詳情請移步至http://requirejs.org/docs/optimization.html。簡單的說,require提供一個叫r.js的檔案,通過本地的node程式(Node.js),執行這個r.js並傳入一些參數,即可自動分析模組互相之間的依賴,以達到合并和壓縮的目的。同樣的,這對於單頁面應用來說是容易的,因為主模組只有一個,但是對於多頁面又如何做呢?好在這個壓縮公用程式支援用一個設定檔來指導壓縮,這樣的話,我們可以編寫下面的配置指令碼build.js:

var build = { appDir: '../js', baseUrl: '.', dir: '../js-built', mainConfigFile: '../js/config.js', modules: [ //First set up the common build layer. {  //module names are relative to baseUrl  name: 'config',  //List common dependencies here. Only need to list  //top level dependencies, "include" will find  //nested dependencies.  include: ["bootstrap", "config","jquery"] }, //Now set up a build layer for each page, but exclude //the common one. "exclude" will exclude nested //the nested, built dependencies from "common". Any //"exclude" that includes built modules should be //listed before the build layer that wants to exclude it. //"include" the appropriate "app/main*" module since by default //it will not get added to the build since it is loaded by a nested //require in the page*.js files. { name:"app/home.index", exclude:["config"] }, { name:"app/blog.create", exclude:["config"] }, ... ]}

通過這個命令來執行壓縮,壓縮的結果將被儲存到js-build目錄:

node.exe r.js -o build.js

build.js指令碼實際上是一個js對象,我們將config加入公用模組,而在各個主模組中將其排除。這樣,所有的公用庫包括config將壓縮成一個js,而主模組又不會包含多餘的config。這樣可想而知,每個頁面在載入時最多隻會下載兩個js,而且公用模組的代碼會“按需執行”。

執行上面的指令碼壓縮,需要安裝有node。可以在從這裡下載。

自動指令碼
但是,隨著主模組的增加,需要隨時跟蹤和修改這個build檔案,這也是很麻煩的。於是,筆者基於node.js開發了一個叫build-build.js的指令碼,用來根據目錄結構自動產生build.js:

fs = require('fs');var target_build = process.argv[2];//console.log(__filename);var pwd = __dirname;var js_path = pwd.substring(0,pwd.lastIndexOf('\\')) + '\\js';console.log('js path : ' + js_path);var app_path = js_path + '\\app';console.log('js app path : ' +app_path);var app_modules = [];var global_modules = [];//build json objectvar build = { appDir: '../js', baseUrl: '.', dir: '../js-built', modules: [ //First set up the common build layer. {  //module names are relative to baseUrl  name: 'config',  //List common dependencies here. Only need to list  //top level dependencies, "include" will find  //nested dependencies.  include: [] } ]}fs.readdir(app_path,function (err,files) { // body... if (err) throw err; for(var i in files){ //put module in app_modules var dotindex = files[i].lastIndexOf('.'); if(dotindex >= 0){  var extension = files[i].substring(dotindex+1,files[i].length);  if(extension == 'js'){  app_modules.push({   name: 'app/' + files[i].substring(0,dotindex),   exclude: ['config']  });  } } } for(var j in app_modules){ build.modules.push(app_modules[j]); }  fs.readdir(js_path,function (err,files){ if (err) throw err; for(var i in files){  //put module in app_modules  var dotindex = files[i].lastIndexOf('.');  if(dotindex >= 0){  var extension = files[i].substring(dotindex+1,files[i].length);  if(extension == 'js'){   global_modules.push(files[i].substring(0,dotindex));  }  }  } build.modules[0].include = global_modules; //console.log(build); var t = pwd + '\\' + target_build; console.log(t); var fd = fs.openSync(t, 'w'); fs.closeSync(fd); var json = JSON.stringify(build); fs.writeFileSync(t, json); });});

這裡的代碼並不複雜,主要是遍曆目錄,產生對象,最後將對象序列化為build.js。讀者可以自行閱讀並修改。最後,編寫一個bat,完成一鍵壓縮功能,build.bat:

@echo offset PWD=%~p0set PWD=%PWD:\=/%cd "D:\node"node.exe %PWD%build-build.js build.jsnode.exe %PWD%r.js -o %PWD%build.jscd %~dp0

這樣,我們就簡單實現了一個方便的多頁面require方案,最後項目目錄可能是這樣的:

Views |--Shared |--_layout.cshtml |--Home |--Index.cshtml |--Blog |--Create.cshtml |--Edit.cshtml |--Detail.cshtml |--Index.cshtmlbuild|--build.js|--r.js|--build-build.js|--build.batjs|--app |--home.index.js |--blog.create.js |--blog.edit.js |--blog.detail.js |--blog.index.js|--jquery.js|--bootstrap.js|--underscore.js|--jquery.ui.js|--jquery.customplugin.js|--config.js|--require.js


您可能感興趣的文章:
  • 一篇文章掌握RequireJS常用知識
  • 小心!AngularJS結合RequireJS做檔案合并壓縮的那些坑
  • RequireJS入門一之實現第一個例子
  • 在JavaScript應用中使用RequireJS來實現消極式載入
  • 使用RequireJS最佳化JavaScript引用代碼的方法
  • 最佳化RequireJS項目的相關技巧總結
  • JavaScript的RequireJS庫入門指南
  • SeaJS 與 RequireJS 的差異對比
  • LABjs、RequireJS、SeaJS的區別

聯繫我們

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