MVC Bundle.Config.cs

    在ASP.NET MVC4中(在WebForm中应该也有),有一个叫做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"));
        }
    }

    其中的bundles.Add是在向网站的BundleTable中添加Bundle项,这里主要有ScriptBundle和StyleBundle,分别用来压缩脚本和样式表。用一个虚拟路径来初始化Bundle的实例,这个路径并不真实存在,然后在新Bundle的基础上Include项目中的文件进去。

    默认情况下,Bundle是会对js和css进行压缩打包的,不过有一个属性可以显式的说明是否需要打包压缩:

BundleTable.EnableOptimizations = true;
    在使用时,在相应位置调用ScriptRender和StyleRender的Render方法:

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    最终用户页面即可达到效果打包压缩效果。
    有一个地方主要注意,在Web.config中,当compilation编译的debug属性设为true时,表示项目处于调试模式,这时Bundle是不会将文件进行打包压缩的,页面中引用的js和css会分散原样的展示在html中,这样做是为了调试时查找问题方便。

  <compilation debug="true" targetFramework="4.5.2" />
    最终部署运行时,将debug设为false就可以看到js和css被打包和压缩了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值