手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >在ASP.NET MVC项目中使用RequireJS库的用法示例
在ASP.NET MVC项目中使用RequireJS库的用法示例
摘要:RequireJS是一个前端模块化开发的流行工具,本身是一个Javascript的库文件,即require.js。RequireJs的主要功...

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多少会有些困惑和不方便。

本文讲解如何在 MVC的结构中应用require,并且给出了压缩脚本,实现半自动化压缩。

将js代码分离
一般而言 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中:

这样会导致页面比较混乱,而且页面}

所有的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,详情请移步至/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,stIndexOf('')) + '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 object var 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 off set PWD=%~p0 set PWD=%PWD:=/% cd "D:node" node.exe %PWD%build-build.js build.js node.exe %PWD%r.js -o %PWD%build.js cd %~dp0

这样,我们就简单实现了一个方便的多页面require方案,最后项目目录可能是这样的:

Views |--Shared |--_layout.cshtml |--Home |--Index.cshtml |--Blog |--Create.cshtml |--Edit.cshtml |--Detail.cshtml |--Index.cshtml build |--build.js |--r.js |--build-build.js |--build.bat 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


【在ASP.NET MVC项目中使用RequireJS库的用法示例】相关文章:

AspNet中使用JQuery boxy插件的确认框

js实现两点之间画线的方法

JS中字符串trim()使用示例

Javascript中For In语句用法实例

javascript中FOREACH数组方法使用示例

在JavaScript中使用开平方根的sqrt()方法

解决 FireFox 下[使用event很麻烦] 的问题.

JavaScript的RequireJS库入门指南

在JavaScript应用中使用RequireJS来实现延迟加载

AngularJS中$interval的用法详解

精品推荐
分类导航