Search code examples
asp.net-core.net-coreasp.net-core-mvcbundling-and-minification

How to bundle different js and css files per controller action/view?


I have site-wide js file (site.js) that goes out with every request.

I have 2 actions on the controller: Action1 and Action2. Each of these actions has a view. Each view references a view-specific js (action1.js and action2.js).

I would like to bundle site.js with action1.js when Action1 method is executing. And when Action2 method, I want to bundle site.js with action2.js.

The bundling should be done at build time.

Is this possible with .Net Core 1.x?


Solution

  • It's possible, but there's a lot of menial work involved, because you'll need to manually describe each view's bundle.

    Everything you need to know can be found in the official documentation, but here's the gist of it:

    1. Action1.cshtml

    I assume that for debugging purposes, you want to include both files on your dev box, while you only want the bundle in production. In your view, you add the following tags:

    <environment names="Development">
        <script src="site.js"></script>
        <script src="action1.js"></script>
    </environment>
    <environment names="Staging,Production">
        <script src="view1.js" asp-append-version="true"></script>
    </environment>
    

    When in development, your two files will be included as is, while in production, the bundled file view1.js will be included.

    asp-append-version is part of the cache busting mechanism: it will append the file's version to each request to that file (details here).

    1. Create your bundled view1.js

    There's a number of various possibilities to create the bundle, but they all revolve around the bundleconfig.json file. The simplest solution uses he BuildBundlerMinifier NuGet package, and simply requires you to add it to your project.

    bundleconfig.json would look like this:

    [
      {
        "outputFileName": "wwwroot/js/view1.js",
        "inputFiles": [
          "wwwroot/js/site.js",
          "wwwroot/js/action1.js"
        ]
      },
    ]
    
    1. Repeat for each view

    This is where things get boring, because you'll need to repeat this for each view.