How to minify CSS / Javascript automatically in ASP.NET MVC5

2

I use Visual Studio 2017, my application runs in ASP.NET MVC5 (Razor), is there a way to minify all the files I choose at the time of "publish"?

    
asked by anonymous 22.03.2018 / 14:32

1 answer

2

You have the Bundle of the framework. Inside your folder App_Start create a class BundleConfig.cs and add:

public static void RegisterBundles(BundleCollection bundles)
{
    //para javascript, você pode fazer vários includes para o mesmo arquivo "scripts"        
    bundles.Add(new ScriptBundle("~/bundles/scripts").Include("~/seuJs.js"));
    //para Css
    bundles.Add(new StyleBundle("~/Content/css").Include("~/seuCss.css"));

    //EnableOptimizations força a minificação mesmo em desenvolvimento, serve para fazer teste se esta minificado corretamente.
    //BundleTable.EnableOptimizations = true;
}

Then just register it on your Application_Start :

BundleConfig.RegisterBundles(BundleTable.Bundles);

In your .cshtml it is necessary to have the javascript or css rendered:

<head>
    @Styles.Render("~/Content/css")
</head>
<body>
   @Scripts.Render("~/bundles/scripts")
</body>
    
22.03.2018 / 15:10