在建立ASP.NET MVC5项目时,默认在App_Start文件夹中建立了BudleConfig.cs文件。css
public class BundleConfig { // For more information on bundling, visit https://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*")); // 使用要用于开发和学习的 Modernizr 的开发版本。而后,当你作好 // ready for production, use the build tool at https://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")); BundleTable.EnableOptimizations = true; //是否打包压缩 } }
在Global.asax 文件Application_Start()方法中调用了BudleConfig类中RegisterBundles方法。jquery
BundleConfig.RegisterBundles(BundleTable.Bundles);web
其中的bundles.Add是在向网站的BundleTable中添加Bundle项,这里主要有ScriptBundle和StyleBundle,分别用来压缩脚本和样式表。用一个虚拟路径来初始化Bundle的实例,这个路径并不真实存在,而后在新Bundle的基础上Include项目中的文件进去。具体的Include语法能够查阅上面提供的官方简介。bootstrap
默认状况下,Bundle是会对js和css进行压缩打包的,不过有一个属性能够显式的说明是否须要打包压缩:学习
BundleTable.EnableOptimizations = true;网站
在Web.config中,当compilation的debug属性设为true时,表示项目处于调试模式,这时Bundle是不会将文件进行打包压缩的。ui
<system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> </httpModules> </system.web>
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js"));
经过ScriptBundle实例添加多个js打包压缩,"~/bundles/bootstrap" 为Bundle名字,Include方法添加多个js文件,中间使用逗号分割。(StyleBundle用来打包压缩css样式文件的,用法同样)spa
视图中调用方法:debug
@Styles.Render("~/Content/css")调试
@Scripts.Render("~/bundles/bootstrap")
补充:“~/Scripts/jquery-{version}.js”,{version}匹配对应文件的任何版本并经过工程配置文件选择正常版本仍是缩小版,具体是web.config中的debug设置,若是为true选择正常版本,false则是缩小版。须要注意的是咱们不能把相同文件的不一样版本号放在一块儿,好比“jquery-1.7.2.js”和“jquery-1.7.1.js”,两个版本号都会被发送给客户端反而形成混淆。