Asp.net MVC中如何使用Bundle合并、压缩js与css文

这篇文章主要介绍Asp.net MVC中如何使用Bundle合并、压缩js与css文,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

一个例子

新建asp.net mvc项目,在App_Start文件夹中你可以看到一个叫做BundleConfig.cs的类,

Asp.net MVC中如何使用Bundle合并、压缩js与css文

该类内容如下:

public class BundleConfig
 {
 // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
 public static void RegisterBundles(BundleCollection bundles)
 {
 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
  "~/Scripts/jquery-{version}.js"));

 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
  "~/Scripts/jquery.validate*"));

 // Use the development version of Modernizr to develop with and learn from. Then, when you're
 // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
 bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
  "~/Scripts/modernizr-*"));

 bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
  "~/Scripts/bootstrap.js",
  "~/Scripts/respond.js"));

 bundles.Add(new StyleBundle("~/Content/css").Include(
  "~/Content/bootstrap.css",
  "~/Content/site.css"));
 }
 }

如上代码所示,压缩和合并分两种对象ScriptBundle和StyleBundle。

namespace System.Web.Optimization
{
 //
 // Summary:
 // Represents a bundle that does Js Minification.
 public class ScriptBundle : Bundle
 {
 //
 // Summary:
 // Initializes a new instance of the System.Web.Optimization.ScriptBundle class
 // that takes a virtual path for the bundle.
 //
 // Parameters:
 // virtualPath:
 // The virtual path for the bundle.
 public ScriptBundle(string virtualPath);
 //
 // Summary:
 // Initializes a new instance of the System.Web.Optimization.ScriptBundle class
 // that takes virtual path and cdnPath for the bundle.
 //
 // Parameters:
 // virtualPath:
 // The virtual path for the bundle.
 //
 // cdnPath:
 // The path of a Content Delivery Network (CDN).
 public ScriptBundle(string virtualPath, string cdnPath);
 }
}

ScriptBundle有两个构造函数,virtualPath:js文件的虚拟路径,cdnPath:js的网络cdn路径。StyleBundle的构造函数的参数与ScriptBundle相同。

在上面的代码片段中你可以看到

  • jquery-{version}.js:其中version是jquery的版本号,version是一个版本号的占位符。

  • jquery.validate*:*通配符,匹配所有。

上面的代码完成后,需要在Global.asax的Application_start事件中对其注册。

Asp.net MVC中如何使用Bundle合并、压缩js与css文

如何使用?

在视图中,通过下面的代码实现对静态文件的引用。

Asp.net MVC中如何使用Bundle合并、压缩js与css文

浏览

Asp.net MVC中如何使用Bundle合并、压缩js与css文

怎么没起作用呢?Bundle默认在调试的情况下,是没有开启打包压缩的,可以通过下面的2中方式进行开启。

Asp.net MVC中如何使用Bundle合并、压缩js与css文

再浏览下

Asp.net MVC中如何使用Bundle合并、压缩js与css文

你会发现Jquery-1.10.2.js该文件在请求中已经不存在了,它已经被打包压缩在jquery?v=版本号,这个文件里面了。

另外一种打开打包压缩的方式,在web.config文件中中:

Asp.net MVC中如何使用Bundle合并、压缩js与css文

以上是“Asp.net MVC中如何使用Bundle合并、压缩js与css文”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!