はじめに
* 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> <script src="@Url.Content("~/bundles/jsHello")" type="text/javascript"></script> <link href="@Url.Content("~/bundles/cssHello")" rel="stylesheet" type="text/css" /> <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}