1、BundleConfig介紹:
在創建ASP.NET MVC5項目時,默認在App_Start文件夾中創建了BudleConfig.cs文件。
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方法。
BundleConfig.RegisterBundles(BundleTable.Bundles);
其中的bundles.Add是在向網站的BundleTable中添加Bundle項,這里主要有ScriptBundle和StyleBundle,分別用來壓縮腳本和樣式表。用一個虛擬路徑來初始化Bundle的實例,這個路徑並不真實存在,然后在新Bundle的基礎上Include項目中的文件進去。具體的Include語法可以查閱上面提供的官方簡介。
默認情況下,Bundle是會對js和css進行壓縮打包的,不過有一個屬性可以顯式的說明是否需要打包壓縮:
BundleTable.EnableOptimizations = true;
在Web.config中,當compilation的debug屬性設為true時,表示項目處於調試模式,這時Bundle是不會將文件進行打包壓縮的。
<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>
2、BundleConfig使用:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js"));
通過ScriptBundle實例添加多個js打包壓縮,"~/bundles/bootstrap" 為Bundle名字,Include方法添加多個js文件,中間使用逗號分割。(StyleBundle用來打包壓縮css樣式文件的,用法一樣)
視圖中調用方法:
@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”,兩個版本號都會被發送給客戶端反而造成混淆。