はじめに
* CSSとJavaScriptをMinify(ミニファイ。リソースの圧縮)化したかったので、 ASP.NET MVCでどう実現するか調べてみた。
Minifyとは?
* JavaScriptやCSSなどで、余分なスペース、改行などの不要なバイトを取り除くこと => パフォーマンスをあげるため。
サンプル
Global.asax.vb
* 既存の処理に以下の「★追加★」を追加Imports System.Web.Mvc Imports System.Web.Optimization Imports System.Web.Routing Public Class MvcApplication Inherits System.Web.HttpApplication Protected Sub Application_Start() AreaRegistration.RegisterAllAreas() RouteConfig.RegisterRoutes(RouteTable.Routes) ' ★追加★ BundleConfig.RegisterBundles(BundleTable.Bundles) End Sub End Class
/App_Start/BundleConfig.vb
* App_Start配下に追加Imports System.Web.Optimization Public Module BundleConfig Public Sub RegisterBundles(ByVal bundles As BundleCollection) bundles.Add(New ScriptBundle("~/bundles/jsHello").Include( "~/Scripts/HelloWorld.js")) bundles.Add(New StyleBundle("~/bundles/cssHello").Include( "~/Content/HelloWorld.css")) End Sub End Module
/Scripts/HelloWorld.js
* Scripts配下にテスト用のJSを追加/** * Hello World.js. */ function sayHello(id, message) { document.getElementById(id).innerText = message; }
/Content/HelloWorld.css
* Content配下にテスト用のCSSを追加/** * Hello World.css. */ div { color:red; }
ビュー(任意のビュー)
<h2>View</h2> <div id="hello"></div> @Scripts.Render("~/bundles/jsHello") @Styles.Render("~/bundles/cssHello") <script> sayHello("hello", "Hello World!!"); </script>
出力結果
<div id="hello"></div> <script src="/bundles/jsHello" type="text/javascript"></script> <link href="/bundles/cssHello" rel="stylesheet" type="text/css" /> <script> sayHello("hello", "Hello World!!"); </script>
/bundles/HelloWorldの中身
★ここに注目★コメント文や無駄な空白が削除されているfunction sayHello(n,t){document.getElementById(n).innerText=t}
/bundles/cssHelloの中身
★ここに注目★コメント文や無駄な空白が削除されているdiv{color:red}
補足:複数指定もできる
' 複数指定もできる bundles.Add(New ScriptBundle("~/bundles/c3").Include( "~/Scripts/d3.js", "~/Scripts/c3.js")) ' 呼び出し <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/c3")" type="text/javascript"></script>
API
JavaScriptのインポート書き出し
@Scripts.Render("~/bundles/jsHello")
CSSのインポート書き出し
@Styles.Render("~/bundles/cssHello")
Minifyの有効化/無効化
1) Web.config の compilation 要素が true / false 2) Global.asax の Application_Start() で BundleTable.EnableOptimizations = true / false
参考文献
http://devadjust.exblog.jp/20061337/http://blog.nnasaki.com/entry/2012/09/08/004330
http://miso-soup3.hateblo.jp/entry/2015/08/24/221113
http://www.pine4.net/Memo/Article/Archives/545
http://monobook.org/wiki/Nancy/Minify_%26_Bundle%E3%82%92%E4%BD%BF%E3%81%86