What Is Bundling and Minification?
Bundling and minification is a process of combining web files, such as style sheets and scripts, into single files that are smaller. You can take all of your CSS files and combine them into a single file that is smaller, you can also do this with your JavaScript files.
Why Bundle and Minify Files?
When you serve smaller files over fewer requests, your website can load faster. This is better for your users and also improves your rankings on Google.
If you run a tool like Google's PageSpeed Tools, you will see they will make suggestions about reducing the file size and quantity of requests.
How To Bundle and Minify Files
First, get the NuGet package for enable bundling and minification for your ASP.NET Core project. The package is: BuildBundlerMinifier.
Once installed in your project, locate all of your CSS and JavaScript files. After you have located all of them and known the correct order they belong in, you can add them to a config file, bundleconfig.json.
Example:
Add the paths to your own CSS files and also your JavaScript files as the "inputFiles". The "outputFileName" is the result of the bundling and minification process. It will be created in your project once a build occurs.
To execute a build, you can build your project in Visual Studio or via command line as: "dotnet restore" then "dotnet build"
These commands will get all of the needed packages for your project and then build it. The build process will do the bundling and minification for you.
You can reference the output file in your project's HTML and only use it for certain environments, for example, only serve the file when it's the staging production environment.
Updating Files
If you update your CSS and JavaScript files and then output the bundled and minified file to the same file name, you can run into problems with browsers caching the file. To allow updates, you should append a version number to the file. ASP.NET can help with this by using: asp-append-version="true" as an attribute.
More Detail
For more detail on bundling and minification in ASP.NET Core, see:
- Microsoft's Bundling and minification in ASP.NET Core docs
- Bundling And Minifying In ASP.NET Core Applications