Tips & Tricks #2: Smart minification with tag helpers in ASP.NET Core
May 14, 2017
When creating a new ASP.NET Core web application, the current template has the following setup for your css and js:
I am not a big fan of this setup because when you create a new .js or .css file you have to add them to the bundleconfig.json and also add them to the layout’s head in the “Development” conditional part.
But then you may run into situations like “oops I added a script to the layout but forgot to add it to the bundler” or “hey, I don’t want all the js files to be loaded on all the pages of my website!”
So let’s see the solution that I am currently using for my ASP.NET Core projects.
1. Switching to gulp
First of all, we are going to change from the default bundler to gulp. We add the following gulpfile.js to our project:
Note: You can go here for a full guide about adding gulp to your project.
What the “min” task does is scan our .js and .css files and create their “.min” equivalent. So for example if we have “page1.js” and “page2.js”, gulp will create (side-by-side) “page1.min.js” and “page2.min.js” respectively.
By keeping the files seperate we can load them individually in our pages when appropriate. Now we can move to the next step.
2. Creating a tag helper to serve the appropriate files
So by now you may be thinking, “But dude, now we have to micromanage all of our .js and .css files!”.
We are going to solve this with a set of tag helpers.
The intent is that when the application is running in “Development”, then the non-minified version of the file should be served for debugging purposes, but for “Staging” and “Production” we definitely want the minified version for performance.
We will create a couple tag helpers that do that automatically.
This is the intended markup:
Notice the minified-auto-switch=“true” part ? That will be our tag helper.
When the above example code would be run in development then “page1.js” would be served, but when we
are running in production then “page1.min.js” would be served instead.
Likewise for css files:
Here is the full code of the tag helpers that implement the above functionality:
Note: To learn more about tag helpers and how to add them to your project, go here.
Now when we create a new js or css file, all we have to do is add our tag helper attribute at the file’s reference tag, as shown above: