Click here to Skip to main content
15,893,722 members
Articles / Web Development / ASP.NET / ASP.NET Core

How to Use Grunt with ASP.NET Core MVC

Rate me:
Please Sign up or sign in to vote.
4.90/5 (7 votes)
25 Jan 2017CPOL13 min read 23.9K   15   7   8
How to use Grunt.js to minify & uglify and configure Task Runner Explorer in ASP.NET Core MVC
In this article, we are going to learn how to use Grunt.js to minify & uglify (JavaScript, cascading style sheets, Images and HTML) and to configure Task Runner Explorer in ASP.NET Core MVC.

What is Grunt.js?

Grunt.js is open source JavaScript toolkit for the automating repetitive tasks in the development process. It is similar to Gulp.js.

There are many tasks already available as Grunt Plugins. You just need to use it and auto your process.

Image 1

Let’s learn how to automate repetitive tasks using Grunt.js.

Topics

  1. Creating Application
  2. Adding package.json file to Project
  3. Downloading Dependencies of Grunt js
  4. Adding Gruntfile.js File to Project
  5. Writing Basic Task to Learn How to Start Using Grunt.js
  6. Installing "Task Runner Explorer" Extension in Visual Studio
  7. Writing Task to Minifying HTML File
  8. Writing Task to Concatenate File JavaScript Files
  9. Writing Task to Uglify and Minify JavaScript
  10. Writing Task to Minify Cascading Style Sheets
  11. Writing Task to Minify / Compress Images
  12. Writing Task to Copy Files From One Folder to Another Folder
  13. Running More than One Task in Sequence Using Grunt.js

Step 1: Creating Application

Now let’s create .NER Core Web Application. Open Visual Studio IDE from start page. Click on New Project link.

Image 2

After clicking on New Project link, it will open a new dialog with Name "New Project". Inside that, from left panel, choose templates, inside that -> choose Visual C# -> inside that, choose .NET Core template, then in middle panel, you will see .NET Core project templates, from templates that choose "ASP.NET Core Web Application (.NET Core)" project templates.

Image 3

After choosing a project template, next we are going to name the project "DemoGrunt". Click on the OK button to create a project, and it will pop up another dialog with a name "New ASP.NET Core Web Application (.NET Core)".

Image 4

Inside this dialog, we are going to choose the "Web Application" project template for create "ASP.NET Core Web Application" and click on the OK button for creating a project.

Below is the complete project view which is newly created:

Image 5

After creating project, the next thing is to add package.json file to project.

Step 2: Adding package.json File in the Project

We are going to add package.json to the project for downloading packages from node package manager.

To add package.json, just right click on "DemoGrunt" project, then select Add from menu list -> then under it, select New Item.

Image 6

After selecting, a new dialog will pop up with a name "Add New Item" as shown below.

In this dialog, we are going to choose "npm Configuration File" and just click on Add button.

Image 7

After clicking on Add button, you can see the package.json file is added to project as shown below:

Image 8

Step 3: Downloading Grunt Packages

We are going to download packages:

  • grunt
  • grunt-contrib-concat
  • grunt-contrib-uglify
  • grunt-contrib-copy
  • grunt-minify-html
  • grunt-contrib-cssmin
  • grunt-tinyimg

Image 9

Code Snippet to Add in package.json

Adding packages to the package.json file in the devDependencies section for downloading packages.

JavaScript
{
	"version": "1.0.0",
	"name": "asp.net",
	"private": true,
    "devDependencies": 
{
        "grunt": "1.0.1",
        "grunt-contrib-concat": "1.0.1",
        "grunt-contrib-uglify": "2.0.0",
        "grunt-contrib-copy": "1.0.0",
        "grunt-minify-html": "2.1.0",
        "grunt-replace": "1.0.1",
        "grunt-contrib-cssmin": "1.0.2",
        "grunt-tinyimg": "1.0.0"
    }
}

Note

  • folder/*.js - will match all the JavaScript files in folder
  • folder/*.css - will match all the CSS files in folder
  • folder/*.html - will match all the HTML files in folder

After adding Dependencies in the package.json file, just saving this file or the entire project, as you save, it will start downloading packages from Node Package Manager (NPM).

Image 10

After downloading Dependencies next, we are going to add a Gruntfile.js file to project.

Step 4: Adding Gruntfile.js File in Project

In this step, we are going to add a Gruntfile.js file to project.

To add Gruntfile.js file, just right click on "DemoGrunt" project, then select Add from menu list -> then under it, select New Item.

Image 11

After selecting, a new dialog will pop up with name "Add New Item" as shown below.

In this dialog, we are going to choose "Grunt Configuration File" and just click on the Add button.

Image 12

After clicking on Add button, it will add Gruntfile.js to project as shown below.

You can see some default code in Gruntfile.js files.

Image 13

Step 5: Writing Basic Task to Learn How to Start using Grunt.js

  1. Now let’s write a simple message to display "Welcome to Grunt js in Visual Studio".

    default’ is the name of the task.

    Below is the Complete Code Snippet of Gruntfile.js

    JavaScript
    module.exports = function (grunt)
    {
        // A very basic default task.
        grunt.registerTask('default', 'Task Description', function () {
            grunt.log.write('Welcome to Grunt js in Visual Studio');
        });
    };

    Now we have to run this task which is written in the Gruntfile.js. For doing that, we need to install extension "Task Runner Explorer".

Step 6: Installing "Task Runner Explorer" Extension in Visual Studio

For installing "Task Runner Explorer", just right-click on the Menu bar of Visual Studio in that, choose Tools Menu, inside that -> choose Extension and Updates.

Image 14

After clicking on Extension and Updates, a new dialog will pop up as shown below in that you need to choose online tab from left, then in Search result, type "Task Runner Explorer"

Image 15

Below is a snapshot after installing "Task Runner Explorer".

After installing, it will ask to restart Visual Studio.

Image 16

After restarting Visual Studio next, we need to open Task Runner Explorer.

To open Task Runner Explorer, just click on Tools menu from Visual Studio and choose Task Runner Explorer Menu.

Image 17

Snapshot of Task Runner Explorer

The Task Runner Explorer contains all tasks of Gruntfile.js and in Tasks, you will find the task which we have created "default" task.

Image 18

Now we are going to run default task. To run it, just right-click on Task Name (default), then two options will appear from that, choose Run option (option with a play button in green color).

Image 19

Below is the snapshot after running a task.

Image 20

Wow, we have completed running the first task. It is easy, right?

After completing task next, we are going to learn about minifying HTML files using gruntfile.js.

Understanding Grunt Properties in Details

Image 21

This information is taken from http://gruntjs.com/configuring-tasks.

Step 7: Writing Task to Minifying HTML File

In this step, we are going to write a task for minifying HTML files. To do that, first I am going to add a folder with name Htmlfiles in the wwwroot folder add them inside that folder, I am going to add an HTML file with name demo.html.

Folder Structure

Image 22

And next, I am going to add another folder in a same wwwroot folder with name Compressedfiles. Here, we are going to store minified HTML files.

Folder Structure

Image 23

After adding HomePage.html file, now let's add some text with space in this file.

Snapshot of HomePage.html File

Image 24

After adding an HTML file with space, next we are going to write a task for minifying this HTML file and write it to other location (Compressedfiles) folder.

Below is the Complete Code Snippet of Gruntfile.js

JavaScript
module.exports = function (grunt) {
    grunt.initConfig({
        // minifyHtml is Task
        minifyHtml:
           {
               //## minifyHtml task configuration goes here ##
               // Html is target
               Html: {
                   src: ['wwwroot/Htmlfiles/**/*.html'],
                   dest: 'wwwroot/Compressedfiles/',
                   expand: true,
                   flatten: true
                    }
           }
    });
    // Load the plugin that provides the "minify html" task.
    grunt.loadNpmTasks("grunt-minify-html");
};

In the above code snippet, we are using ["grunt-minify-html"] plugin to minify HTML files along with this, we had also provided src (source) and dest (destination) folder path from where it is going to take HTML files (source) to minify and after minifying it, we are going to write it in a different folder in project (destination).

Understanding Code Snippet of Gruntfile.js

  1. The first step contains wrapper function and all Grunt related code that must be written inside this function.
    JavaScript
    module.exports = function (grunt) {
        // Do grunt-related things in here
    };
  2. In the second step, we are going to Initialize a configuration object:
    JavaScript
    module.exports = function (grunt) {
        grunt.initConfig({
    
       });
    };
  3. In the third step, we are going to write a task "minifyHtml" inside the initConfig method:
    JavaScript
    module.exports = function (grunt) {
        grunt.initConfig({
         
       minifyHtml:
            {
                 // minifyHtml is Task
    
                     }
       });
    };
  4. In the fourth step, we are going to write Target ("Html") inside Task "minifyHtml"
    JavaScript
    module.exports = function (grunt) {
        grunt.initConfig({
         
       minifyHtml:
            {
              Html: {
                   // Html is Target
                    }
                     }
       });
    };

    Note: One Task can have many targets inside it.

  5. In the fifth step, we are going to configure properties source [src], destination [dest], expand, and flatten.
    JavaScript
    module.exports = function (grunt) {
        grunt.initConfig({
            // minifyHtml is Task
            minifyHtml:
               {
                   //## minifyHtml task configuration goes here ##
                   // Html is target
                   Html: {
                       src: 'wwwroot/Htmlfiles/**/*.html',
                       dest: 'wwwroot/Compressedfiles/',
                       expand: true,
                       flatten: true
                        }
               }
        });
    };
  6. Loading Grunt plugins and tasks "grunt-minify-html".
    JavaScript
    module.exports = function (grunt) {
        grunt.initConfig({
            // minifyHtml is Task
            minifyHtml:
               {
                   //## minifyHtml task configuration goes here ##
                   // Html is target
                   Html: {
                       src: 'wwwroot/Htmlfiles/**/*.html',
                       dest: 'wwwroot/Compressedfiles/',
                       expand: true,
                       flatten: true
                        }
               }
        });
        // Load the plugin that provides the "minify html" task.
        grunt.loadNpmTasks("grunt-minify-html");
    };

Options

  • Source [Src] = the path from where we are going to get all html files from Htmlfiles folder to minify
  • Destination [Dest] = the path where we want to store all minified html files output in Compressedfiles folder

Finally, save Gruntfile.js and open Task Runner Explorer.

To run, just right click on "minifyHtml" task and from the list of Tasks, choose Run.

Image 25

After running task, let’s have look at Compressedfile folder where minified HTML file is stored.

Folder Structure

Image 26

Output of Compressed File /Minified File

Image 27

Step 8: Writing Task to Concatenate JavaScript Files

In this part, we are going to learn how to concatenate JavaScript files. For doing that, we are going to add four JavaScript files in a folder and then we are going to concat all JavaScript files into one single JavaScript file.

Folder Structure

Image 28

In every JavaScript file, I am going to add a single JavaScript function in it such that we can understand how it concats files.

Image 29

After writing all functions in JavaScript individual files, now let's write the task on Gruntfile.js to concat all these files to one single file.

One thing we have missed here is where we are going to store all concatenated JavaScript files for storing that file, I am going to create a new folder with name "ConcatenatedJsfiles" in which all JavaScript files which are concatenated will store in this folder.

Folder Structure

Image 30

Below is the Complete Code Snippet of Gruntfile.js

JavaScript
module.exports = function (grunt) {
    grunt.initConfig({
        // concat is Task
        concat:
          {
              // all is Target
              all:
             {
                 src: ['wwwroot/js/**/*.js'],
                 dest: 'wwwroot/ConcatenatedJsfiles/combined.js'
             }
          }
    });
    // Load the plugin that provides the "concat files" task.
    grunt.loadNpmTasks("grunt-contrib-concat");
};
  • Source [Src] = the path from where we are going to get all JavaScript files from JS folder to concat
  • Destination [Dest] = the path where we want to store all Concatenated JavaScript files output in ConcatenatedJsfiles folder.

In the above code snippet, we are using ["grunt-contrib-concat"] plugin to concat JavaScript files along with this, we had also provided src (source) and dest (destination) folder path from where it is going to take JavaScript files (source) to concat and after concating, it is going to write it at different folder in project (destination).

Finally, save Gruntfile.js and open Task Runner Explorer.

To run, just right click on "concat" task and from the list of menu, choose Run menu.

Snapshot of Task Runner Explorer

Image 31

After running task, let’s have look at "ConcatenatedJsfiles" folder where concatenated JavaScript file is stored.

Folder Structure

Image 32

Output of Concatenated JavaScript Files

Image 33

Step 9: Writing Task to Uglify and Minify JavaScript

In this step, we are going to write a task for uglifying and minifying JavaScript file for doing that first, I am going to add a folder with name MinifiedJavascriptfiles in wwwroot folder in this folder, all uglifying and minifying JavaScript files will be stored and we are going to get all JavaScript files from "Js" folder for uglifying and minify.

Folder Structure

Image 34

JavaScript File to Minify

Image 35

Below is the Complete Code Snippet of Gruntfile.js

JavaScript
module.exports = function (grunt)
{
    grunt.initConfig({
        // uglify is Task
        uglify:
           {
               // js is Target 
               js:
                  {
                      //Source of files
                      src: ['wwwroot/js/**/*.js'],
                      //Destination of files
                      dest: 'wwwroot/MinifiedJavascriptfiles/Calculation.js'
                  }
           }
    });
    // Load the plugin that provides the "uglify|Minify" task.
    grunt.loadNpmTasks("grunt-contrib-uglify");
};

In the above code snippet, we are using ["grunt-contrib-uglify"] plugin to uglify and minify JavaScript files along with this, we had also provided src (source) and dest (destination) folder path from where it is going to take JavaScript files (source) to uglify and minify and after uglifying and minifying, it is going to write it at different folder in project (destination).

Finally, save Gruntfile.js and open Task Runner Explorer.

To run, just right click on "uglify" task and from the list of menu, choose Run menu.

Snapshot of Task Runner Explorer

Image 36

After running task, let’s have look at "MinifiedJavascriptfiles" folder where minified JavaScript file is stored.

Folder Structure

Image 37

Output of Minified JavaScript Files

Image 38

Step 10: Writing Task to Minify Cascading Style Sheets

In this step, we are going to write task for minifying cascading style sheets file. For doing that, first I am going to add a folder with name MinifiedCssfiles in wwwroot folder in this folder all minified cascading style sheets files will be stored and we are going to get all cascading style sheets files from "css" folder for minifying.

Image 39

Cascading Style Sheets File to Minify

Image 40

Below is the Complete Code Snippet of Gruntfile.js

JavaScript
module.exports = function (grunt) {
    grunt.initConfig({
        // cssmin is Task
        cssmin:
           {
               // css is Target 
               css:
                  {
                      //Source of files
                      src: ['wwwroot/css/**/*.css'],
                      //Destination of files
                      dest: 'wwwroot/MinifiedCssfiles/site.min.css'
                  }
           }
    });
    // Load the plugin that provides the "Minify" task.
    grunt.loadNpmTasks("grunt-contrib-cssmin");
};

In the above code snippet, we are using ["grunt-contrib-cssmin"] plugin to minify CSS (Cascading Style Sheet) files along with this, we had also provided src (source) and dest (destination) folder path from where it is going to take CSS (Cascading Style Sheet) files (source) to minify and after minify, it is going to write it in a  different folder in project (destination).

Finally, save Gruntfile.js and open Task Runner Explorer. To run, just right click on "Cssmin" and from the list of menu, choose Run menu.

Snapshot of Task Runner Explorer

Image 41

After running task, we have to see "MinifiedCssfiles" folder where minified cascading style sheets file is stored.

Folder Structure

Image 42

Output of Minified CSS Files

Image 43

Step 11: Writing Task to Minify / Compress Images

In this step, we are going to Compress Images. To do this, I am going to use the "grunt-tinyimg" plugin. Next, we are going to create a folder with name Compressimages in a wwwroot folder. In this folder, all Compress images will be stored and we are going to get all Images from the "images" folder for compressing.

Image 44

Below is the Complete Code Snippet of Gruntfile.js

JavaScript
module.exports = function (grunt) {
    grunt.initConfig({
        // tinyimg is Task
        tinyimg:
           {
               // minifyimage is Target
               minifyimage:
                  {
                      // Source of files
                      src: ['wwwroot/images/**/*.{png,jpg,gif,svg}'],
                      // Destination of files
                      dest: 'wwwroot/Compressimages/',
                      expand: true,
                      flatten: true
                  }
           }
    });
    // Load the plugin that provides the "tinyimg" task.
    grunt.loadNpmTasks("grunt-tinyimg");
};

In the above code snippet, we are using ["grunt-tinyimg"] plugin to minify Images files. Along with this, we had also provided src (source) and dest (destination) folder path from where it is going to take images (source) to minify images and after minifying, we are going to write it at different folder in project (destination).

Finally, save Gruntfile.js and open Task Runner Explorer.

To run, just right click on "tinyimg" and from the list of menu, choose Run menu.

Snapshot of Task Runner Explorer

Image 45

Snapshot of Images before Compressing

Image 46

Snapshot of Images after Compressing

Image 47

Step 12: Writing Task to Copy Files From One Folder to Another Folder

In this step, we are going to write a task for copying files from one folder to another folder.

For the demo, I am going to show how to copy HTML files from one folder to another folder in the project.

Package used "grunt-contrib-copy".

I have added Htmlfiles folder inside the wwwroot folder where I need to move my HTML files from the TempHtmlFiles folder located outside of the wwwroot folder.

Image 48

Below is Complete Code Snippet of Gruntfile.js

JavaScript
module.exports = function (grunt) {
    grunt.initConfig({
        // copy is Task
        copy: {
            // html is Target 
            html:
                {
                    //Source of files
                    src: 'TempHtmlFiles/**/*.html',
                    //Destination of files
                    dest: 'wwwroot/Htmlfiles/',
                    // Options
                    expand: true,
                    flatten: true,
                    filter: 'isFile'
                }
        }
    });
    // Load the plugin that provides the "copy" task.
    grunt.loadNpmTasks("grunt-contrib-copy");
};

In the above code snippet, we are using a ["grunt-contrib-copy"] plugin to copy files along with this, we had also provided src (source) and dest (destination) folder path from where it is going to copy files (source) and after copying it is going to write it at different folder in project (destination).

Finally, save Gruntfile.js and open Task Runner Explorer.

To run, just right click on "copy" Task and from the Tasks list of menu and choose Run menu.

Snapshot of Task Runner Explorer

Image 49

Snapshot of Copied Files in Htmlfiles Folder

Image 50

Step 13: Running More Than One Task in Sequence Using Grunt.js

In this step, we are going to learn how to run more than on one task in particular sequence.

For doing that, we are going to use the registerTask() method of Grunt.js and this method has three overloading.

Parameters

  • name: The name of the task
  • Callback: A function that is run when the task is executed
  • Message: Log a message
  • Array: A string array of task names

Image 51

Image 52Image 53

Below Snapshot of Code Snippet Shows How to Run More Than One Task in Sequence Using Grunt.js

Image 54

In the above code snippet, we are using two plugins ["grunt-contrib-copy, grunt-contrib-uglify"], one for copying files and another for uglifying JavaScript files.

We are going to run two tasks in sequence, first copying files task and another is uglifying JavaScript files task. In copying files task, we are going to copy files from one folder to another folder and in uglify task, we are going uglify and minify JavaScript files and then write it at a different folder in the project.

Finally, save Gruntfile.js and open Task Runner Explorer.

To run, just right click on aliased task "all" and from the list of menu, choose Run menu.

Snapshot of Task Runner Explorer

Image 55

Snapshot of Copied Files in Htmlfiles folder

Image 56

Finally, we have completed a short journey of learning using of Grunt js with ASP.NET Core MVC, I hope you have enjoyed it.

By using Grunt plugin, you can create different tools which are going to help in day to day process and reduce time to work on core process of your project.

History

  • 25th January, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Microsoft Most Valuable Professional
Code Project Most Valuable Author
C# Corner Most Valuable Professional

I am Senior Technical lead Working on.Net Web Technology
ASP.NET MVC,.Net Core,ASP.NET CORE, C#, SQL Server, MYSQL, MongoDB, Windows

Comments and Discussions

 
Questiongreat article Pin
Luis Fernando Camacho Camacho27-Feb-18 15:38
Luis Fernando Camacho Camacho27-Feb-18 15:38 
QuestionOne request for few articles on unit testing Pin
Mou_kol1-Sep-17 0:11
Mou_kol1-Sep-17 0:11 
AnswerRe: One request for few articles on unit testing Pin
Saineshwar Bageri1-Sep-17 21:55
Saineshwar Bageri1-Sep-17 21:55 
QuestionRegarding Grunt and gulp Pin
Mou_kol1-Sep-17 0:07
Mou_kol1-Sep-17 0:07 
QuestionThanks!! Pin
Member 1326459617-Jun-17 2:33
Member 1326459617-Jun-17 2:33 
AnswerRe: Thanks!! Pin
Saineshwar Bageri17-Jun-17 5:30
Saineshwar Bageri17-Jun-17 5:30 
ya you can also add entire folder this process
PraiseThanks for the article Pin
adonis_abril25-Jan-17 9:56
adonis_abril25-Jan-17 9:56 
GeneralRe: Thanks for the article Pin
Saineshwar Bageri25-Jan-17 16:58
Saineshwar Bageri25-Jan-17 16:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.