asp.net-core-mvcasp.net-bundlingweboptimizer

Can WebOptimizer pipeline be created in a separate file?


I am working on a MVC project with .NET 6. I am using WebOptimizer for bundling and minification. The documentation mentions creating a bundling pipeline, like below.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddWebOptimizer(pipeline =>
    {
        pipeline.MinifyJsFiles("js/a.js", "js/b.js", "js/c.js");
    });
}

I want all the bundling rules/pipeline to reside in a separate class/file. And reference that class/file in services.AddWebOptimizer() . This way Startup.cs is much more readabile and


Solution

  • You can create a static separate class like below:

    using Microsoft.Extensions.DependencyInjection;
    using WebOptimizer;
    public static class WebOptimizerConfig
    {
        public static void ConfigureBundles(IAssetPipeline pipeline)
        {
            pipeline.AddCssBundle("bundle.css", "/css/site.css", "/css/other.css");
            pipeline.MinifyJsFiles("js/a.js", "js/b.js", "js/c.js");
    
            //more bundling rules...
        }
    }
    

    Then reference this class like below:

    services.AddWebOptimizer(pipeline =>
    {
        WebOptimizerConfig.ConfigureBundles(pipeline);
    });