How can I add Bundle Config to Startup.cs for resources to use in Razor Views?

Bundling and Minification as it existed in MVC5 no longer exists in MVC Core.

Your options are (without delving into the Node ecosystem - which is just as valid but would introduce more concepts):

  • Use the bundling and minification Visual Studio extension.
  • Or use the command line bundling and minification dotnet tool.

Both of these tools operate on the same infrastructure under the covers. They use a bundleConfig.json file to describe the structure of your bundles (what files go in, what file comes out, wether to include sourcemaps, etc.)

Explanations of these two concepts are also available via the documentation.

Instead of having a call to @Scripts.Render() which would produce links to either minified or unminified resources depending on your build environment, you can use taghelpers to swap between links to minified and unminified resources. For example:

<environment names="Development">
    <script src="~/unminified.js"></script>
</environment>
<environment names="Staging,Production">
    <script src="~/bundledandminified.min.js"></script>
</environment>

I needed the run-time bundling features of System.Web.Optimization (to be able to do dynamic Less compilation 😈) so I implemented a NET Core replacement for that and now I've decided to publish it under MIT license.

If you want to use it, first you need to install an implementation NuGet package:

dotnet add package Karambolo.AspNetCore.Bundling.NUglify

or

dotnet add package Karambolo.AspNetCore.Bundling.WebMarkupMin

Whichever minifier library you prefer.

Then you need to register it in the DI container in Startup.ConfigureServices():

services.AddBundling()
    .UseDefaults(_env)
    .UseNUglify(); // or .WebMarkupMin(), respectively

The field _env is a reference to IHostingEnvironment, you can inject it in the constructor.

Now you can configure your bundles in the Configure() method as follows:

app.UseBundling(bundles =>
{
    bundles.AddJs("/jquery.js")
        .Include("/Scripts/jquery-*.js");

    bundles.AddJs("/jqueryval.js")
        .Include("/Scripts/jquery.validate*");

    // and so on...
});

Note the tildes and the "/bundles" prefix removed (since it's added automatically) and the extensions added to the bundle path. It's required to use the correct extension which corresponds to the output of the bundle.

Add the following to your _ViewImports.cshtml:

@using Karambolo.AspNetCore.Bundling.ViewHelpers
@addTagHelper *, Karambolo.AspNetCore.Bundling

In the Razor views you can use the familiar syntax:

@await Scripts.RenderAsync("~/bundles/jquery.js")
@await Scripts.RenderAsync("~/bundles/jqueryval.js")

or the new tag helper syntax:

<script src="~/bundles/jquery.js"></script>
<script src="~/bundles/jqueryval.js"></script>

Note that in the views you must add the tilde and the prefix. For more on this and other details please refer to the project page.