ASP.NET MVC BundleConfig介紹和使用

一、BundleConfig介紹:

在建立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>

二、BundleConfig使用:

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」,兩個版本號都會被髮送給客戶端反而形成混淆。

相關文章
相關標籤/搜索