ASP.Net Core bundle, minification and gzip Css and Javascript files

Do Dung
6 min readMay 6, 2020

In this article, I will guide you on how to bundle, minification and gzip static files in ASP.Net Core (all versions). With a web application, the performance load page is very important so we need to reduce page size to make the website load faster. To reduce page size we have many things to do eg: custom img, bundle Js, CSS, hosting, server… But in this article, I only guide to bundle js and CSS files.

1. Setup Environment & Create project

We need a visual studio editor to code. I will use VS2019 to create this example. You can use a lower version.

I will create the ASP.Net Core project with the latest version 3.1. You don’t forget that bundle, minification and gzip CSS and Js files you can do in any framework and version of .Net So you can choose any version of .Net core.

Okay, I just created a project web application Asp.Net Core with the name BundleStatics.

2. Install bundle & minification

This step is very important because this plugin will auto bundle when you press Ctrl+S.

After created the project done, in the menu bar of the visual studio select Extentions > Manager Extentions.

Select Online item on the left side and type “ minifier” into the search bar on the right side and you will see the results have a Bundler & Minifier extension and click the Download button to install.

After finish download, you need to close the visual studio to continue to install Bundler & Minifier extension.

Click the Modify button and wait for the install finish and then open VS it ready to use.

3. Bundle and minification static files

First, we need to create bundleconfig.json at the root of the project. This file will contain a setting for the bundle file.

With the bundle, you can join many files into one file, remove all space…. It helps reduce the size of static files.

* Syntax of bundle file:

[
{
"outputFileName": "wwwroot/styles/libs-css.css",
"inputFiles":
[
"wwwroot/css/site.css",
"wwwroot/css/basic.css"
]
},
{
"outputFileName": "wwwroot/scripts/libs-js.js",
"inputFiles":
[
"wwwroot/lib/jquery/dist/jquery.js",
"wwwroot/js/site.js"
]
}
]

In that :
outputFileName : setting the new path file, you can set a bundle file to another folder.

inputFiles: List path file need bundle.

After config file is done, press Ctrl+S all file bundle will auto-generate as below image:

Okay, Here you can import new js and CSS into your webpage but with a min file that files are still heavy. Below is a demo compare between bundle, minify and gzip file :

You can see that the gzip file is three times smaller than the minify file. So using the gzip file will help the website load better than.

4. Configure gzip file

To make a gzip file we will use Gulpjs. To install Gulpjs you can see the guideline of Glup here.

4.1. Install package of Gulpjs

You need to install Node.js on your computer before installing Gulpjs.

You can download recommended from the home page of NodeJs here.

After checking Nodejs and NPM done, open CMD and point to the folder containing the project.

Run below command to install CLI of Gulpjs :

npm install --global gulp-cli

Next step we need to create a package.json file to store information about packages. Enter below command :

Enter some info you need eg: name, author, version, description, license… after the finish we will get files as below :

{
"name":"package.json",
"version":"1.0.0",
"description":"gzip file",
"main":"gulpfile.js",
"scripts":{
"test":"echo \"Error: no test specified\" && exit 1"
},
"author":"QuizDev",
"license":"ISC"
}

Next step we need to install three packages of Gulpjs :

npm install --save-dev gulp 
npm install --save-dev rimraf
npm install --save-dev gulp-gzip

After the install is finished you will see dependencies of the project and you will see all packages installed.

4.2. Create gulpfile.js file

I will create file gulpfile.js at the root of the project.

Content of this file will contain as bellow with 7 steps:

//Step 1: Import gulp libraries
var gulp = require("gulp"),
rimraf = require("rimraf"),
gzip = require("gulp-gzip");
//Step 2: Setting path contain css and js file
var paths = {
webroot: "./wwwroot/"
};
//Step 3: Setting path file will get to gzip
paths.minJs = paths.webroot + "scripts/**/*.min.js"; // only get min file from scripts folder
paths.minCss = paths.webroot + "styles/**/*.min.css";
//Step 4: Folder will store new gzip file
paths.concatGzJsDest = paths.webroot + "scripts";
paths.concatGzCssDest = paths.webroot + "styles";
//Step 5: Create command to clear gzip
gulp.task("clean:gzJs", done => rimraf(paths.concatGzJsDest, done));
gulp.task("clean:gzCss", done => rimraf(paths.concatGzCssDest, done));
gulp.task("clean", gulp.series(["clean:gzCss", "clean:gzJs"]));
//Step 6: Create command to gzip css & js file
gulp.task('gzip:gzJs', function () {
return gulp.src(paths.minJs)
.pipe(gzip())
.pipe(gulp.dest(paths.concatGzJsDest));
});
gulp.task('gzip:gzCss', function () {
return gulp.src(paths.minCss)
.pipe(gzip())
.pipe(gulp.dest(paths.concatGzCssDest));
});
//Step 7: Execute Gzip
gulp.task("gzip", gulp.series(["gzip:gzCss", "gzip:gzJs"]));
// A 'default' task is required by Gulp v4
gulp.task("default", gulp.series(["gzip"]));

*Note: Gulp js supports all bundle, minify and gzip types, so you can use it to do all but use bundleconfig to bundle, minify I feel better than.

4.3. Generate Gzip file

To generate a gzip file. Select View > Other Windows > Task Runner Explorer

If you see as below image you need restart visual studio:

After reset VS you will see some option as below :

To clear all Js & CSS bundle, double click clear option. To gzip all Js and CSS double click gzip option, default option help gzip all CSS & Js by the default setting of Gulp.

And see the result :

Okay, now we import gz file to the HTML page:

But the CSS file does not accept and apply CSS to the web page.

This problem because the browser can not auto read gz file, we need to add a middleware to accept gzip header content.

To add middleware we need to custom UseStaticFiles() function in the Configure() method of Startup.cs file.

Change :

app.UseStaticFiles();

To

app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
IHeaderDictionary headers = context.Context.Response.Headers;
string contentType = headers["Content-Type"];
if (contentType == "application/x-gzip")
{
if (context.File.Name.EndsWith("js.gz"))
{
contentType = "application/javascript";
}
else if (context.File.Name.EndsWith("css.gz"))
{
contentType = "text/css";
}
headers.Add("Content-Encoding", "gzip");
headers["Content-Type"] = contentType;
}
}
});

Build the code and reload the web page to see the result:

Now I show you see the load time of gzip and min files with small compare load file:

You can see the load time of gzip less than 6 times when compared with min file. This is the main reason Gzip is better and powerful.

5. Summary

In this article, I just guide how to bundle, minification and gzip static files in ASP.Net Core. This solution can apply for all versions of .Net core.

All source code I have been uploaded into GitHub. You can refer here.

**Update : If you download code from GitHub to your local computer you will need to run npm install to install and update package.json file packages.

Happy code!!!

I hope this article is helpful to you. Originally published at https://quizdeveloper.com.

--

--