.netasp.net-coreasp.net-core-mvcminifybundling-and-minification

How to minify in .net core mvc view?


On the website I made with .net core mvc. When we open the site and click on the page source view, how can we do the long codes as shown in the second picture, in the form of minify?

enter image description here

enter image description here


Solution

  • Adding Web Markup Min to ASP.NET Core application

    WebMarkupMin is a very mature minifier, not just for HTML but also XML and XHTML, as well as script and style tags embedded in your HTML. They provide multiple NuGet packages for hooking up your ASP.NET applications, both for ASP.NET 4.x using MVC, HttpModules, WebForms and ASP.NET Core.

    Step 1. Install package WebMarkupMin.AspNetCoreX

    My project is ASP.NET Core 5, so I choose to install WebMarkupMin.AspNetCore5.

    enter image description here

    Step 2. Register in your application's Startup.Configure method

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...
            app.UseStaticFiles();
    
            app.UseWebMarkupMin();
    
            app.UseRouting();
            ...
        }
    

    Step 3. Register services to the IoC container

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
    
            services.AddWebMarkupMin(
                options =>
                {
                    options.AllowMinificationInDevelopmentEnvironment = true;
                    options.AllowCompressionInDevelopmentEnvironment = true;
                })
                .AddHtmlMinification(
                    options =>
                    {
                        options.MinificationSettings.RemoveRedundantAttributes = true;
                        options.MinificationSettings.RemoveHttpProtocolFromAttributes = true;
                        options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true;
                    })
                .AddHttpCompression();
        }
    

    Test result

    Before:

    enter image description here

    After:

    enter image description here



    Configure bundling and minification

    The MVC and Razor Pages project templates provide a solution for bundling and minification consisting of a JSON configuration file. A third-party tool is a great fit when your development workflow requires processing beyond bundling and minification—such as linting and image optimization. By using design-time bundling and minification, the minified files are created prior to the app's deployment. Bundling and minifying before deployment provides the advantage of reduced server load. You can check details from official document here.