Bundling and Minification in ASP.NET Core MVC

SPONSOR AD

Bundling and Minification in ASP.NET Core MVC

In this article, I will discuss Bundling and Minification in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing ASP.NET Core MVC with EF Core DB First Approach with Examples.

Bundling and Minification in ASP.NET Core MVC

Bundling and minification are two important techniques used in ASP.NET Core MVC to improve the performance of web applications. These techniques are primarily used to reduce the number of server requests and the size of the requested assets (like CSS, JavaScript, etc.), making web pages load faster.

Bundling in ASP.NET Core MVC

Bundling is the process of combining multiple files into a single file. This reduces the number of HTTP requests needed to load a web page, as each script or stylesheet file typically requires a separate request. In ASP.NET Core MVC, bundling can be achieved through various means:

  • Using Built-in Support (prior to ASP.NET Core 3.0): Earlier versions of ASP.NET Core provided built-in support for bundling through Microsoft’s Microsoft.AspNetCore.Mvc package. However, this support was deprecated in ASP.NET Core 3.0.
  • Using Third-Party Libraries: For ASP.NET Core 3.0 and later versions, you can use third-party libraries such as BuildBundlerMinifier, WebOptimizer, or other npm-based tools like Gulp or Webpack. These tools allow more customization and are widely used in the industry.
Minification in ASP.NET Core MVC

Minification is the process of removing unnecessary characters (like white spaces, new lines, and comments) from source code without changing its functionality. This reduces the file size, allowing for faster loading times.

SPONSOR AD
  • Built-in Support: Like bundling, minification also had built-in support in earlier versions of ASP.NET Core but was later deprecated.
  • Third-Party Tools: For minification in ASP.NET Core 3.0 and later, you can use the same third-party libraries mentioned for bundling. These tools often provide both bundling and minification capabilities.
Example to Understand Bundling and Minification in ASP.NET Core MVC:

First, create an ASP.NET Core Web Application using the Model View Controller Project template. Once you create the project, then please add a few CSS and JavaScript files within css and js folder of your wwwroot folder, as shown in the below image:

Example to Understand Bundling and Minification in ASP.NET Core MVC

Now, let us add some dummy content to the above CSS and JS files. Don’t go with the content. Just copy and paste the same with the respective files. This is just for the demo purpose.

Site.css:
html {
  font-size: 14px;
}

@media (min-width: 768px) {
  html {
    font-size: 16px;
  }
}

html {
  position: relative;
  min-height: 100%;
}

body {
  margin-bottom: 60px;
}
StyleSheet2.css
/* Section styles */
section {
    padding: 20px;
    margin: 20px 0;
}

/* Classes for buttons */
.btn {
    display: inline-block;
    background: #555;
    color: #fff;
    padding: 10px 15px;
    margin: 5px 0;
    text-decoration: none;
    border-radius: 5px;
    transition: background 0.3s;
}
MyStyleSheet.css
/* Basic reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f4f4f4;
}

/* Header styles */
header {
    background: #333;
    color: #fff;
    padding: 1rem 0;
    text-align: center;
}
Site.js
// Function to change the background color of the body
function changeBackgroundColor(color) {
    document.body.style.backgroundColor = color;
}

// Function to display a welcome message
function displayWelcomeMessage() {
    alert('Welcome to the dummy JavaScript test!');
}
JavaScript2.js
// Event listener for a button click
document.getElementById('testButton').addEventListener('click', function () {
    console.log('Test button clicked!');
    changeBackgroundColor('lightblue');
});

// Function to calculate and display the sum of two numbers
function calculateSum() {
    var num1 = parseInt(document.getElementById('num1').value, 10);
    var num2 = parseInt(document.getElementById('num2').value, 10);
    var sum = num1 + num2;
    document.getElementById('sumResult').innerText = 'Sum: ' + sum;
}
MyJavaScript.js
// Toggle visibility of an element
function toggleVisibility(elementId) {
    var element = document.getElementById(elementId);
    if (element.style.display === 'none') {
        element.style.display = 'block';
    } else {
        element.style.display = 'none';
    }
}
Using the above CSS and JS Files in our Views:

Suppose we want to use the above CSS and JS files in our views. Then, we can include them in the respective views. But as we will use these files in all our views, it is better and advisable to reference these files in the _Layout.cshtml file. So, add the following within the head section of your _Layout.cshtml file.

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/css/mystylesheet.css" rel="stylesheet" />
<link href="~/css/stylesheet2.css" rel="stylesheet" />

<script src="~/js/javascript2.js"></script>
<script src="~/js/myjavascript.js"></script>
<script src="~/js/site.js"></script>
Run and Test the application:

Now, run the application and verify the Network tab, and you will see that the client (i.e., browser) issues 6 different requests to the server to load the 6 (3 CSS Files and 2 JS Files) files as shown in the image below.

Example Without using Bundling and Minification in ASP.NET Core MVC

The point that you need to remember is that each request will take some time. So, the higher the number of requests between the client and server, the more time it will take to load the page. We can overcome this problem, and we can improve the page loading time by using the concept called Bundling and Minification in the ASP.NET Core MVC Application. Let us proceed and see how we can implement bundling and Minification in our ASP.NET Core MVC Application.

SPONSOR AD
Setting Up BuildBundlerMinifier in ASP.NET Core:

Let us proceed and understand the step-by-step process to implement Bundling and Minification in the ASP.NET Core MVC Application.

Install Required NuGet Packages

Ensure you have the required NuGet packages. In ASP.NET Core 6, the primary package you might need is BuildBundlerMinifier. You can install this package via the NuGet Package Manager Console as follows:

Install-Package BuildBundlerMinifier

Once you install the package, it should be visible in the Packages folder, as shown in the image below.

Install-Package BuildBundlerMinifier

Configure Services in the Program.cs

In ASP.NET Core 6 and later, the startup configuration is usually done in the Program.cs file. You must ensure the application is set up to serve static files.

app.UseStaticFiles(); // Enable serving static files

Create a Bundle Configuration File

Create a file named bundleconfig.json in the root of your project. This file defines the bundling and minification settings.

[
  {
    "outputFileName": "wwwroot/js/MySite.min.js",
    "inputFiles": [
      "wwwroot/js/site.js",
      "wwwroot/js/MyJavaScript.js",
      "wwwroot/js/JavaScript2.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "includeInProject": true
  },
  {
    "outputFileName": "wwwroot/css/MySite.min.css",
    "inputFiles": [
      "wwwroot/css/site.css",
      "wwwroot/css/MyStyleSheet.css",
      "wwwroot/css/StyleSheet2.css"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "includeInProject": false
  }
]
Understanding bundleconfig.json File

outputFileName: This property specifies the path and name of the output file that will be generated after the bundling and/or minification process. For example, if you set “outputFileName”: “wwwroot/js/bundle.js”, it means all the JavaScript files specified in inputFiles will be combined and possibly minified into a single file named bundle.js, located in the wwwroot/js directory.

SPONSOR AD

inputFiles: This is an array of strings where each string represents the path to an input file to be included in the bundle. The files listed here are combined in the order they are specified to create the output file. For example: “inputFiles”: [“wwwroot/js/script1.js”, “wwwroot/js/script2.js”] will combine script1.js and script2.js into a single file.

minify: This property is an object that specifies the settings for minification. Minification is the process of removing unnecessary characters (like whitespace, newlines, and comments) from the code without changing its functionality. This reduces the file size and, thus, the load time. For example, the setting “minify”: {“enabled”: true} enables minification. You can also specify more detailed options for JavaScript and CSS minification, such as renameLocals for JavaScript or CSS and JS for respective file types. The renameLocals property, when set to true, enables the renaming of local variables and functions to shorter names during the minification process. This renaming helps reduce the size of the JavaScript files further.

includeInProject: This property indicates whether the generated output file should be included in the project. When set to true, the output file is added to the project file structure and will be visible in solutions like Visual Studio. For example, “includeInProject”: true means the output file (outputFileName) will be included in your project structure.

sourceMap: The sourceMap property is a boolean setting that specifies whether source maps should be generated for the bundled and minified files. When set to true, a source map file is created alongside the minified file. A source map is essentially a file that maps the transformed, combined, or minified source to the original source files. It contains information about the original positions of the code before minification or bundling.

Now, instead of specifying the individual input file names, we can use the * as shown below:

[
  {
    "outputFileName": "wwwroot/js/MySite.min.js",
    "inputFiles": [
      "wwwroot/js/*.js"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "includeInProject": true
  },
  {
    "outputFileName": "wwwroot/css/MySite.min.css",
    "inputFiles": [
      "wwwroot/css/*.css"
    ],
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    "includeInProject": false
  }
]
Build the Project:

When you build your project, the BuildBundlerMinifier package will automatically process your bundleconfig.json file and generate the specified output files. Once you build the project, then you will see the respective files created, as shown in the image below:

Build the Project

Reference Bundled Files in Views

In your Razor views (e.g., _Layout.cshtml), reference the bundled files instead of individual CSS or JS files. So, add the following two files instead of 6 files:

<link href="~/css/mysite.min.css" rel="stylesheet" />
<script src="~/js/mysite.min.js"></script>

Now, run the application, and you should see the two requests made by the client, as shown in the below image.

Bundling and Minification in ASP.NET Core MVC Applications with Examples

SPONSOR AD

Note: As we are reducing the number of requests between the client and server and reducing the file size by implementing minification, it will definitely improve the application’s performance.

Environment-Based Bundling and Minification

As a best practice, your app’s bundled and minified files should be used in a production environment. During development, the original files make for easier debugging of the app. Specify which files to include in your pages by using the Environment Tag Helper in your views. The Environment Tag Helper only renders its contents when running in specific environments.

<environment include="Development">
    <link href="~/css/site.css" rel="stylesheet" />
    <link href="~/css/mystylesheet.css" rel="stylesheet" />
    <link href="~/css/stylesheet2.css" rel="stylesheet" />

    <script src="~/js/javascript2.js"></script>
    <script src="~/js/myjavascript.js"></script>
    <script src="~/js/site.js"></script>
</environment>
<environment exclude="Development">
    <link href="~/css/mysite.min.css" rel="stylesheet" />
    <script src="~/js/mysite.min.js"></script>
</environment>
When should you use Bundling and Minification in ASP.NET Core MVC?

Bundling and minification are two important techniques used in web development, including in ASP.NET Core MVC, to improve page load times and overall website performance. Here’s when you should use them:

  • In Production Environments: These techniques are particularly important in a production environment where performance is crucial. During development, it’s often beneficial to keep files separate for ease of debugging and maintenance.
  • For Large Projects: In projects with many JavaScript, CSS, and HTML files, bundling helps reduce the number of server requests needed to load these resources, which is beneficial for performance.
  • High-Traffic Websites: Websites that expect high traffic benefit significantly from reduced bandwidth usage and faster load times, which can be achieved through bundling and minification.
  • Mobile-Friendly Sites: Since mobile devices often have slower internet connections and lower performance than desktops, optimizing resource loading is critical for mobile-friendly websites.
Why Use Bundling and Minification in ASP.NET Core MVC?
  • Improved Load Times: Bundling reduces the number of HTTP requests to the server as multiple files are combined into a single file. Minification reduces the size of each file by removing unnecessary characters (like whitespace and comments), resulting in faster download times.
  • Reduced Bandwidth: Smaller file sizes mean less bandwidth usage, which benefits both the server and the user, especially those with limited data plans or slower internet connections.
  • Better Cache Management: The browser can cache bundled files, meaning repeat visits to your site will load faster as the browser does not need to re-download the resources.
  • Optimized Parsing and Execution: Minified files are faster for browsers to parse and execute. This is particularly important for JavaScript files.
Best Practices
  • Environment-Specific Bundling: Set up your configuration to bundle and minify assets in production while leaving them unbundled in development for easier debugging.
  • Source Maps: Use source maps during development to help debug your JavaScript and CSS files even after bundling.
  • Optimization: Regularly review your bundled files to ensure they are optimized in size and load order.
  • Test Thoroughly: Bundling and minification can sometimes cause unexpected issues, especially in JavaScript, due to variable scoping or strict mode. Thorough testing is essential.

In the next article, I will discuss Bundling and Minification in ASP.NET Core Using WebOptimizer with Examples. In this article, I try to explain Bundling and Minification in ASP.NET Core MVC Applications with Examples. I hope you enjoy this article on Bundling and Minification in ASP.NET Core MVC.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *