编程那点事编程那点事

专注编程入门及提高
探究程序员职业规划之道!

ASP.NET MVC Bundle详解(压缩js和css)

什么是Bundle?

Bundle是MVC 4 提供的一个新特性,一个在 View 和 Layout 中用于组织优化浏览器请求的 CSS 和 JavaScript 文件的技术。讲直观一点,就是Bundle是用来压缩js和css的。

怎么配置Bundle?

1、App_Start下新建BundleConfig.cs类

大致内容,如下图所示

BundleConfig.cs类 内容

我也精简了部分代码,代码如下

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        //jquery v1.11.3
        bundles.Add(new ScriptBundle("~/js/jquery")
            .Include("~/static/admin/plugins/jquery/jquery.min.js"));
        //bootstrap 3.3.6
        bundles.Add(new ScriptBundle("~/js/bootstrap")
            .Include("~/static/admin/plugins/bootstrap/js/bootstrap.min.js"));
        bundles.Add(new StyleBundle("~/css/bootstrap")
            .Include("~/static/admin/plugins/bootstrap/css/bootstrap.css"));
    }
}

2、配置Global.asax

在Global.asax文件中新加如下代码

BundleConfig.RegisterBundles(BundleTable.Bundles);

怎么使用Bundle?

在需要使用的页面,类似下面这样调用代码即可

@Scripts.Render("~/js/jquery")
@Scripts.Render("~/js/easyui")
@Styles.Render("~/css/easyui")

下面是,使用截图

如何在web界面使用Bundle

在使用的过程中,直接@Scripts和@Styles的形式,可能会报错:当前上下文中不存在名称“Scripts”,解决方法,请看这篇文章:当前上下文中不存在名称“Scripts”

最后,默认情况下Bundle是不会对js和css压缩打包的,需要你手动开启,开启方式是配置web.confg文件

compilation中的debug设置为true,Bundle不会压缩js和css

compilation中的debug设置为false,Bundle压缩js和css

配置compilation的debug值

使用效果,看以下截图

未开启压缩前,源代码如下图所示

Bundle未启用之前的效果

开启压缩后,源代码如下图所示

Bundle启用后的效果

此时,你可以看下script和link的内容,也是被压缩了的。

未经允许不得转载: 技术文章 » .NET编程 » ASP.NET MVC Bundle详解(压缩js和css)