ASP.NET Core MVC Bundling & Minification

There are many ways of bundling & minification of client side resources (JavaScript and CSS files). Most common ways are:

ABP offers a simple, dynamic, powerful, modular and built-in way.

Volo.Abp.AspNetCore.Mvc.UI.Bundling Package

This package is already installed by default with the startup templates. So, most of the time, you don’t need to install it manually.

Install the Volo.Abp.AspNetCore.Mvc.UI.Bundling nuget package to your project:

  1. install-package Volo.Abp.AspNetCore.Mvc.UI.Bundling

Then you can add the AbpAspNetCoreMvcUiBundlingModule dependency to your module:

  1. using Volo.Abp.Modularity;
  2. using Volo.Abp.AspNetCore.Mvc.UI.Bundling;
  3. namespace MyCompany.MyProject
  4. {
  5. [DependsOn(typeof(AbpAspNetCoreMvcUiBundlingModule))]
  6. public class MyWebModule : AbpModule
  7. {
  8. //...
  9. }
  10. }

Razor Bundling Tag Helpers

The simplest way of creating a bundle is to use abp-script-bundle or abp-style-bundle tag helpers. Example:

  1. <abp-style-bundle name="MyGlobalBundle">
  2. <abp-style src="/libs/bootstrap/css/bootstrap.css" />
  3. <abp-style src="/libs/font-awesome/css/font-awesome.css" />
  4. <abp-style src="/libs/toastr/toastr.css" />
  5. <abp-style src="/styles/my-global-style.css" />
  6. </abp-style-bundle>

This bundle defines a style bundle with a unique name: MyGlobalBundle. It’s very easy to understand how to use it. Let’s see how it works:

  • ABP creates the bundle as lazy from the provided files when it’s first requested. For the subsequent calls, it’s returned from the cache. That means if you conditionally add the files to the bundle, it’s executed only once and any changes of the condition will not effect the bundle for the next requests.
  • ABP adds bundle files individually to the page for the development environment. It automatically bundles & minifies for other environments (staging, production…).
  • The bundle files may be physical files or virtual/embedded files.
  • ABP automatically adds version query string to the bundle file URL to prevent browsers from caching when the bundle is being updated. (like ?_v=67872834243042 - generated from last change date of the related files). The versioning works even if the bundle files are individually added to the page (on the development environment).

Importing The Bundling Tag Helpers

This is already imported by default with the startup templates. So, most of the time, you don’t need to add it manually.

In order to use bundle tag helpers, you need to add it into your _ViewImports.cshtml file or into your page:

  1. @addTagHelper *, Volo.Abp.AspNetCore.Mvc.UI.Bundling

Unnamed Bundles

The name is optional for the razor bundle tag helpers. If you don’t define a name, it’s automatically calculated based on the used bundle file names (they are concatenated and hashed). Example:

  1. <abp-style-bundle>
  2. <abp-style src="/libs/bootstrap/css/bootstrap.css" />
  3. <abp-style src="/libs/font-awesome/css/font-awesome.css" />
  4. <abp-style src="/libs/toastr/toastr.css" />
  5. @if (ViewBag.IncludeCustomStyles != false)
  6. {
  7. <abp-style src="/styles/my-global-style.css" />
  8. }
  9. </abp-style-bundle>

This will potentially create two different bundles (one incudes the my-global-style.css and other does not).

Advantages of unnamed bundles:

  • Can conditionally add items to the bundle. But this may lead to multiple variations of the bundle based on the conditions.

Advantages of named bundles:

  • Other modules can contribute to the bundle by its name (see the sections below).

Single File

If you need to just add a single file to the page, you can use the abp-script or abp-style tag without a wrapping in the abp-script-bundle or abp-style-bundle tag. Example:

  1. <abp-script src="/scripts/my-script.js" />

The bundle name will be scripts.my-scripts for the example above (“/“ is replaced by “.”). All bundling features are work as expected for single file bundles too.

Bundling Options

If you need to use same bundle in multiple pages or want to use some more powerful features, you can configure bundles by code in your module class.

Creating A New Bundle

Example usage:

  1. [DependsOn(typeof(AbpAspNetCoreMvcUiBundlingModule))]
  2. public class MyWebModule : AbpModule
  3. {
  4. public override void ConfigureServices(ServiceConfigurationContext context)
  5. {
  6. Configure<AbpBundlingOptions>(options =>
  7. {
  8. options
  9. .ScriptBundles
  10. .Add("MyGlobalBundle", bundle => {
  11. bundle.AddFiles(
  12. "/libs/jquery/jquery.js",
  13. "/libs/bootstrap/js/bootstrap.js",
  14. "/libs/toastr/toastr.min.js",
  15. "/scripts/my-global-scripts.js"
  16. );
  17. });
  18. });
  19. }
  20. }

You can use the same name (MyGlobalBundle here) for a script & style bundle since they are added to different collections (ScriptBundles and StyleBundles).

After defining such a bundle, it can be included into a page using the same tag helpers defined above. Example:

  1. <abp-script-bundle name="MyGlobalBundle" />

This time, no file defined in the tag helper definition because the bundle files are defined by the code.

Configuring An Existing Bundle

ABP supports modularity for bundling as well. A module can modify an existing bundle that is created by a depended module. Example:

  1. [DependsOn(typeof(MyWebModule))]
  2. public class MyWebExtensionModule : AbpModule
  3. {
  4. public override void ConfigureServices(ServiceConfigurationContext context)
  5. {
  6. Configure<AbpBundlingOptions>(options =>
  7. {
  8. options
  9. .ScriptBundles
  10. .Configure("MyGlobalBundle", bundle => {
  11. bundle.AddFiles(
  12. "/scripts/my-extension-script.js"
  13. );
  14. });
  15. });
  16. }
  17. }

It’s not possible to configure unnamed bundle tag helpers by code, because their name are not known at the development time. It’s suggested to always use a name for a bundle tag helper.

Bundle Contributors

Adding files to an existing bundle seems useful. What if you need to replace a file in the bundle or you want to conditionally add files? Defining a bundle contributor provides extra power for such cases.

An example bundle contributor that replaces bootstrap.css with a customized version:

  1. public class MyExtensionGlobalStyleContributor : BundleContributor
  2. {
  3. public override void ConfigureBundle(BundleConfigurationContext context)
  4. {
  5. context.Files.ReplaceOne(
  6. "/libs/bootstrap/css/bootstrap.css",
  7. "/styles/extensions/bootstrap-customized.css"
  8. );
  9. }
  10. }

Then you can use this contributor as like below:

  1. services.Configure<AbpBundlingOptions>(options =>
  2. {
  3. options
  4. .ScriptBundles
  5. .Configure("MyGlobalBundle", bundle => {
  6. bundle.AddContributors(typeof(MyExtensionGlobalStyleContributor));
  7. });
  8. });

You can also add contributors while creating a new bundle.

Contributors can also be used in the bundle tag helpers. Example:

  1. <abp-style-bundle>
  2. <abp-style type="@typeof(BootstrapStyleContributor)" />
  3. <abp-style src="/libs/font-awesome/css/font-awesome.css" />
  4. <abp-style src="/libs/toastr/toastr.css" />
  5. </abp-style-bundle>

abp-style and abp-script tags can get type attributes (instead of src attributes) as shown in this sample. When you add a bundle contributor, its dependencies are also automatically added to the bundle.

Contributor Dependencies

A bundle contributor can have one or more dependencies to other contributors. Example:

  1. [DependsOn(typeof(MyDependedBundleContributor))] //Define the dependency
  2. public class MyExtensionStyleBundleContributor : BundleContributor
  3. {
  4. //...
  5. }

When a bundle contributor is added, its dependencies are automatically and recursively added. Dependencies added by the dependency order by preventing duplicates. Duplicates are prevented even if they are in separated bundles. ABP organizes all bundles in a page and eliminates duplications.

Creating contributors and defining dependencies is a way of organizing bundle creation across different modules.

Contributor Extensions

In some advanced scenarios, you may want to do some additional configuration whenever a bundle contributor is used. Contributor extensions works seamlessly when the extended contributor is used.

The example below adds some styles for prism.js library:

  1. public class MyPrismjsStyleExtension : BundleContributor
  2. {
  3. public override void ConfigureBundle(BundleConfigurationContext context)
  4. {
  5. context.Files.AddIfNotContains("/libs/prismjs/plugins/toolbar/prism-toolbar.css");
  6. }
  7. }

Then you can configure AbpBundleContributorOptions to extend existing PrismjsStyleBundleContributor.

  1. Configure<AbpBundleContributorOptions>(options =>
  2. {
  3. options
  4. .Extensions<PrismjsStyleBundleContributor>()
  5. .Add<MyPrismjsStyleExtension>();
  6. });

Whenever PrismjsStyleBundleContributor is added into a bundle, MyPrismjsStyleExtension will also be automatically added.

Accessing to the IServiceProvider

While it is rarely needed, BundleConfigurationContext has a ServiceProvider property that you can resolve service dependencies inside the ConfigureBundle method.

Standard Package Contributors

Adding a specific NPM package resource (js, css files) into a bundle is pretty straight forward for that package. For example you always add the bootstrap.css file for the bootstrap NPM package.

There are built-in contributors for all standard NPM packages. For example, if your contributor depends on the bootstrap, you can just declare it, instead of adding the bootstrap.css yourself.

  1. [DependsOn(typeof(BootstrapStyleContributor))] //Define the bootstrap style dependency
  2. public class MyExtensionStyleBundleContributor : BundleContributor
  3. {
  4. //...
  5. }

Using the built-in contributors for standard packages;

  • Prevents you typing the invalid resource paths.
  • Prevents changing your contributor if the resource path changes (the dependant contributor will handle it).
  • Prevents multiple modules adding the duplicate files.
  • Manages dependencies recursively (adds dependencies of dependencies, if necessary).

Volo.Abp.AspNetCore.Mvc.UI.Packages Package

This package is already installed by default in the startup templates. So, most of the time, you don’t need to install it manually.

Standard package contributors are defined in the Volo.Abp.AspNetCore.Mvc.UI.Packages NuGet package. To install it to your project:

  1. install-package Volo.Abp.AspNetCore.Mvc.UI.Packages

Then add the AbpAspNetCoreMvcUiPackagesModule module dependency to your own module;

  1. using Volo.Abp.Modularity;
  2. using Volo.Abp.AspNetCore.Mvc.UI.Bundling;
  3. namespace MyCompany.MyProject
  4. {
  5. [DependsOn(typeof(AbpAspNetCoreMvcUiPackagesModule))]
  6. public class MyWebModule : AbpModule
  7. {
  8. //...
  9. }
  10. }

Bundle Inheritance

In some specific cases, it may be needed to create a new bundle inherited from other bundle(s). Inheriting from a bundle (recursively) inherits all files/contributors of that bundle. Then the derived bundle can add or modify files/contributors without modifying the original bundle. Example:

  1. services.Configure<AbpBundlingOptions>(options =>
  2. {
  3. options
  4. .StyleBundles
  5. .Add("MyTheme.MyGlobalBundle", bundle => {
  6. bundle
  7. .AddBaseBundles("MyGlobalBundle") //Can add multiple
  8. .AddFiles(
  9. "/styles/mytheme-global-styles.css"
  10. );
  11. });
  12. });

Themes

Themes uses the standard package contributors to add library resources to page layouts. Themes may also define some standard/global bundles, so any module can contribute to these standard/global bundles. See the theming documentation for more.

Best Practices & Suggestions

It’s suggested to define multiple bundles for an application, each one is used for different purposes.

  • Global bundle: Global style/script bundles are included to every page in the application. Themes already defines global style & script bundles. Your module can contribute to them.
  • Layout bundles: This is a specific bundle to an individual layout. Only contains resources shared among all the pages use the layout. Use the bundling tag helpers to create the bundle as a good practice.
  • Module bundles: For shared resources among the pages of an individual module.
  • Page bundles: Specific bundles created for each page. Use the bundling tag helpers to create the bundle as a best practice.

Establish a balance between performance, network bandwidth usage and count of many bundles.

See Also