Created
August 8, 2014 14:01
-
-
Save MrScruffy04/4a0827dfbf3ee2c19a0a to your computer and use it in GitHub Desktop.
Allows one to minify JS and CSS within a Razor View in Nancy. See usage at the bottom of the source.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Nancy.ViewEngines.Razor | |
{ | |
using System; | |
using Microsoft.Ajax.Utilities; | |
using SquishIt.Framework; | |
using SquishIt.Framework.Utilities; | |
public static class OptimizationExtensions | |
{ | |
public static IHtmlString JsMinify<TModel>(this HtmlHelpers<TModel> helpers, Func<object, object> markup) | |
{ | |
if (helpers == null || markup == null) | |
{ | |
return NonEncodedHtmlString.Empty; | |
} | |
var sourceJs = (markup.DynamicInvoke(helpers.RenderContext) ?? String.Empty).ToString(); | |
if (new DebugStatusReader().IsDebuggingEnabled()) | |
{ | |
return new NonEncodedHtmlString(sourceJs); | |
} | |
var minifier = new Minifier(); | |
var minifiedJs = minifier.MinifyJavaScript(sourceJs, new CodeSettings | |
{ | |
EvalTreatment = EvalTreatment.MakeImmediateSafe, | |
PreserveImportantComments = false | |
}); | |
return new NonEncodedHtmlString(minifiedJs); | |
} | |
public static IHtmlString CssMinify<TModel>(this HtmlHelpers<TModel> helpers, Func<object, object> markup) | |
{ | |
if (helpers == null || markup == null) | |
{ | |
return NonEncodedHtmlString.Empty; | |
} | |
var sourceCss = (markup.DynamicInvoke(helpers.RenderContext) ?? String.Empty).ToString(); | |
if (new DebugStatusReader().IsDebuggingEnabled()) | |
{ | |
return new NonEncodedHtmlString(sourceCss); | |
} | |
var minifier = new Minifier(); | |
var minifiedCss = minifier.MinifyStyleSheet(sourceCss, new CssSettings | |
{ | |
CommentMode = CssComment.None | |
}); | |
return new NonEncodedHtmlString(minifiedCss); | |
} | |
} | |
} | |
/* | |
<script type="text/javascript">@(Html.JsMinify(@<text> | |
// JS code here | |
</text>))</script> | |
or | |
<style type="text/css">@(Html.CssMinify(@<text> | |
/* CSS rules here * / | |
</text>))</style> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the MVC version here: https://gist.github.com/MrScruffy04/6908211