Click here to Skip to main content
14,145,240 members
Click here to Skip to main content
Add your own
alternative version

Stats

12.5K views
7 bookmarked
Posted 25 Jan 2017
Licenced CPOL

How to Use Grunt with ASP.NET Core MVC

, 25 Jan 2017
Rate this:
Please Sign up or sign in to vote.
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 just you need to use it and auto your process.

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

Topic

  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

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.

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)".

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.

After creating project next think 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.

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.

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

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

Code snippet to add in package.json

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

{
	"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)

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.

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.

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.

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 Complete Code Snippet of Gruntfile.js

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.

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"

Below is snapshot after installing "Task Runner Explorer".

After installing it will ask to restart Visual Studio.

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.

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.

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

Below is snapshot after running a task.

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

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 then inside that folder I am going to add an HTML file with name demo.html.

Folder structure

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

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

Snapshot of HomePage.html file

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 Complete Code Snippet of Gruntfile.js

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 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 minify it going to write it at different folder in project (destination).

Understanding code snippet of Gruntfile.js

  1. In the first step contains wrapper function and all Grunt related code must be written inside this function.
module.exports = function (grunt) {
    // Do grunt-related things in here
};
  1. In a second step, we are going to Initialize a configuration object
module.exports = function (grunt) {
    grunt.initConfig({

   });
};
  1. In a third step, we are going to write a task "minifyHtml" inside the initConfig Method
module.exports = function (grunt) {
    grunt.initConfig({
     
   minifyHtml:
        {
             // minifyHtml is Task

                 }
   });
};
  1. In a fourth step, we are going to write Target ("Html") inside Task "minifyHtml"
module.exports = function (grunt) {
    grunt.initConfig({
     
   minifyHtml:
        {
          Html: {
               // Html is Target
                }
                 }
   });
};

Note: One Task can have many targets inside it.

  1. In a Fifth step, we are going to configure properties source [src], destination [dest], expand, and flatten.
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
                    }
           }
    });
};
  1. Loading Grunt plugins and tasks "grunt-minify-html"
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 and choose Run.

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

Folder structure

Output of Compressed file /Minified file

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

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

After writing all function in JavaScript individual files now let write the task on Gruntfile.js to concat this all files to one single file.

One thing we have missed here is where we are going to store all Concatenated JavaScript file 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

Below is Complete Code Snippet of Gruntfile.js

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 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 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 and choose Run menu.

Snapshot of Task Runner Explorer

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

Folder structure

Output of Concatenated JavaScript files

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

JavaScript File to minify

Below is Complete Code Snippet of Gruntfile.js

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 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 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 and choose Run menu.

Snapshot of Task Runner Explorer

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

Folder structure

Output of Minified JavaScript files

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.

Cascading style sheets File to minify

Below is Complete Code Snippet of Gruntfile.js

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 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 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 "Cssmin" and from the list of menu and choose Run menu.

Snapshot of Task Runner Explorer

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

Folder structure

Output of Minified Css files

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.

Below is Complete Code Snippet of Gruntfile.js

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 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 and choose Run menu.

Snapshot of Task Runner Explorer

Snapshot of Images before Compressing

Snapshot of Images after Compressing

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.

Below is Complete Code Snippet of Gruntfile.js

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 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

Snapshot of copied files in Htmlfiles folder

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 3 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.

Below Snapshot of code snippet shows how to run more than one task in sequence using Grunt.js

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

We are going to run 2 task 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 and choose Run menu.

Snapshot of Task Runner Explorer

Snapshot of copied files in Htmlfiles folder

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.

License

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

Share

About the Author

Saineshwar Bageri
Software Developer (Senior)
India India
Microsoft Most Valuable Professional
Code Project Most Valuable Author
C# Corner Most Valuable Professional

I am Software Developer Working on.Net Web Technology
ASP.NET MVC,.Net Core,ASP.NET CORE, C#, SQL server, MYSQL, MongoDB, Windows

I Also do Freelancing on.Net Technology

You may also be interested in...

Pro

Comments and Discussions

 
Questiongreat article Pin
Luis Fernando Camacho Camacho27-Feb-18 15:38
memberLuis Fernando Camacho Camacho27-Feb-18 15:38 
QuestionOne request for few articles on unit testing Pin
Mou_kol1-Sep-17 0:11
memberMou_kol1-Sep-17 0:11 
AnswerRe: One request for few articles on unit testing Pin
Saineshwar Bageri1-Sep-17 21:55
member Saineshwar Bageri1-Sep-17 21:55 
QuestionRegarding Grunt and gulp Pin
Mou_kol1-Sep-17 0:07
memberMou_kol1-Sep-17 0:07 
QuestionThanks!! Pin
Member 1326459617-Jun-17 2:33
memberMember 1326459617-Jun-17 2:33 
AnswerRe: Thanks!! Pin
Saineshwar Bageri17-Jun-17 5:30
member Saineshwar Bageri17-Jun-17 5:30 
PraiseThanks for the article Pin
adonis_abril25-Jan-17 9:56
memberadonis_abril25-Jan-17 9:56 
GeneralRe: Thanks for the article Pin
Saineshwar Bageri25-Jan-17 16:58
member 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190518.1 | Last Updated 25 Jan 2017
Article Copyright 2017 by Saineshwar Bageri
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid