Saineshwar Bageri">
Click here to Skip to main content
15,166,980 members
Articles / Web Development / ASP.NET
Article
Posted 10 Jan 2017

Stats

37K views
352 downloads
11 bookmarked

How to Use Gulp with ASP.NET Core MVC

Rate me:
Please Sign up or sign in to vote.
4.79/5 (17 votes)
10 Jan 2017CPOL12 min read
Use Gulp.js to minify & uglify and to configure Task Runner Explorer in ASP.NET Core MVC
In this article, we are going to learn how to use Gulp.js to minify & uglify (JavaScript, cascading style sheets and HTML) and to configure Task Runner Explorer in ASP.NET Core MVC.

Introduction

The first question that comes to mind is what is Gulp.js?

Gulp.js is an open source JavaScript toolkit for the automating task in the development process.

In our daily projects, we develop lots of JavaScript, Cascading Style Sheet, HTML files, but to minify or beautify this file, we go to some website, there we upload files to minify or beautify files.

If we can automate this process in Visual Studio, what would be your reaction? "Wow," right?

Let’s learn how to automate this process using gulp.js and enjoy.

Image 1

Topics

  1. Creating Application
  2. Adding package.json File in the Project
  3. Downloading Dependencies of gulp js
  4. Adding gulp.js file in Project
  5. Writing Basic Task to Learn How to Use Start Using gulp.js
  6. Installing "Task Runner Explorer" Extension in Visual Studio
  7. Adding HTML file to Project and Writing Task to Minifying HTML File
  8. Writing Task for Concatenate file JavaScript Files
  9. Writing Task to Minify JavaScript
  10. Writing Task to Minify Cascading Style Sheets
  11. Writing Task to Change File Extension of JavaScript Files and Cascading Style Sheet
  12. Automating Task
  13. History

Step 1: Creating Application

Now, let’s create a .NET 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 the middle of your pane, you will see .NET Core project templates, from templates that choose "ASP.NET Core Web Application (.NET Core)" project templates.

Image 3

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

Image 4

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

Below is a complete project view which is newly created.

Image 5

After creating a 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 "DemoGulp" project, then select Add from menu list -> then under it, select New Item.

Image 6

After selecting a new dialog, a pop up with the name "Add New Item" will appear 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

After adding a package.json file to project, next we are going to download packages for gulp.

Step 3: Downloading gulp Packages

We are going to download packages:

  • gulp
  • rimraf
  • gulp-concat
  • gulp-cssmin
  • gulp-uglify
  • gulp-minify-html
  • gulp-ext-replace

Details about Packages

Image 9

Code Snippet to Add in package.json

This is the code snippet which we are going to add in the package.json devDependencies part.

JavaScript
"devDependencies": {
    "gulp": "^3.9.1",
    "rimraf": "^2.5.4",
    "gulp-concat": "2.6.1",
    "gulp-cssmin": "^0.1.7",
    "gulp-uglify": "^2.0.0",
    "gulp-minify-html": "^1.0.6",
    "gulp-ext-replace": "^0.3.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

Snapshot of package.json

Image 10

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 11

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

Step 4: Adding gulpfile.js File in Project

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

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

Image 12

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

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

Image 13

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

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

Image 14

Step 5: Writing Basic Task to Learn How to Start Using gulp.js

  1. The first step is to load module.
    JavaScript
    var gulp = require('gulp');
  2. In the second step, let’s have a look at task how it looks like:
    JavaScript
    gulp.task('default', function ()
    {
       // place code for your default task here
    });
    

    default’ is the name of the task and you can write task inside this function.

  3. Now let’s write a simple message to display "Welcome to gulp js".
    JavaScript
    var gulp = require('gulp');
    
    gulp.task('default', function ()
    {
      // place code for your default task here
      console.log('Welcome to gulp js in Visual Studio');
    });
    

Snapshot of Gulpfile.js

Image 15

Now we have to run this task which is written in glupfile.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 Menu bar of Visual Studio, in that, choose Tools Menu, inside that -> choose Extension and Updates.

Image 16

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 Results, type "Task Runner Explorer".

Image 17

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

After installing, it will ask to restart Visual Studio.

Image 18

After restarting Visual Studio, next we need to open Task runner explorer.

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

Image 19

Snapshot of Task Runner Explorer

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

Image 20

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

Image 21

Below is a snapshot after running a task.

Image 22

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

After completing task, next, we are going to learn how to minify an HTHL file using gulpfile.js.

Step 7: Writing Task to Minifying HTML File

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

Folder Structure

Image 23

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

Folder Structure

Image 24

After adding the demo.html file, now let add some text with space in this file.

Snapshot of demo.html File

Image 25

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

Complete Code Snippet of gulpfile.js

JavaScript
var gulp = require('gulp');

//Using package to minify html 
minifyHtml = require("gulp-minify-html");

var paths = {
    webroot: "./wwwroot/"
};
//Getting Path of Htmlfiles to Minifying
paths.html = paths.webroot + "Htmlfiles/**/*.html";

//Path to Writing minified Files after Minifying
paths.Destination = paths.webroot + "Compressedfile";

gulp.task('minify-html', function ()
{   // path to your files
     gulp.src(paths.html)
    // Minifying files
    .pipe(minifyHtml())
    // Writing files to Destination
    .pipe(gulp.dest(paths.Destination));
});

// Main task to Call for Minifying html files
gulp.task("demo", ["minify-html"]);

Understanding Code Snippet of gulpfile.js

  1. In the first step, we are going to load module.
    JavaScript
    var gulp = require('gulp');
    
    //Using package to minify html 
    minifyHtml = require("gulp-minify-html");
  2. In the second step, we are going to declare variable with name "paths" which is going to store the path of "wwwroot".
    JavaScript
    var paths = {
        webroot: "./wwwroot/"
    };
  3. In the third step, we are going to declare path to get files from "Htmlfiles" folder.
    JavaScript
    //Getting Path of Htmlfiles to Minifying
    paths.html = paths.webroot + "Htmlfiles/**/*.html";
  4. In the fourth step, we are going to declare path to writing Compressed files in "Compressedfile" folder.
    JavaScript
    //Path to Writing minified Files after Minifying
    paths.Destination = paths.webroot + "Compressedfile";
  5. In the fifth step, we are going to write task ('minify-html') for getting all HTML files and use minify package to minify them and write it to destination folder which we have created.
    JavaScript
    gulp.task('minify-html', function ()
    {   // path to your files
         gulp.src(paths.html)
        // Minifying files
        .pipe(minifyHtml())
        // Writing files to Destination
        .pipe(gulp.dest(paths.Destination));
    });
  6. In the sixth step, we are going to write main task such that we can run another task sequentially
    JavaScript
    gulp.task("demo", ["minify-html"]);

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

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

Snapshot of Task Runner Explorer

Image 26

After running task, we have to see Compressedfile folder where minified HTML file is stored.

Folder Structure

Image 27

Output of Compressed File

Image 28

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 JavaScript file.

Folder Structure

Image 29

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 30

After writing all the functions in JavaScript individual files, now let's write the task on gulpfile.js to concat all files into 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 31

Complete Code Snippet of gulpfile.js

JavaScript
var gulp = require('gulp');

//Using package to concat files 
concat = require("gulp-concat");

var paths = {
    webroot: "./wwwroot/"
};

//Getting Path of Javascript files 
paths.js = paths.webroot + "js/**/*.js";

//Path to Writing concatenated Files after concatenating
paths.Destination = paths.webroot + "ConcatenatedJsfiles";

var newconcat = "concatmain.js"; // Name of new file

// Task Name [concatfiles]
gulp.task('concatfiles', function ()
{   // path to your files
     gulp.src(paths.js)
    // concat files
    .pipe(concat(newconcat))
    // Writing files to Destination
    .pipe(gulp.dest(paths.Destination));
});

// Main task to Call for concatenating js files
gulp.task("demo", ["concatfiles"]);

Understanding Code Snippet of gulpfile.js

  1. In the first step, we are going to load module.
    JavaScript
    var gulp = require('gulp');
    
    //Using package to concat files 
    concat = require("gulp-concat");
  2. In the second step, we are going to declare variable with name "paths" which is going to store the path of "wwwroot".
    JavaScript
    var paths = {
        webroot: "./wwwroot/"
    };
  3. In the third step, we are going to declare path to get JavaScript files from "Js" folder.
    JavaScript
    //Getting Path of Javascript files 
    paths.js = paths.webroot + "js/**/*.js";
  4. In forth step we are going declare path to store Concatenated files in "ConcatenatedJsfiles" folder.
    JavaScript
    //Path to Writing concatenated Files after concatenating
    paths.Destination = paths.webroot + "ConcatenatedJsfiles";
  5. In the fifth step, we are going to declare a variable with name newconcat and to this variable, we are going to assign the name of new JavaScript file (concatmain.js).
    JavaScript
    var newconcat = "concatmain.js"; // Name of new file
  6. In the sixth step, we are going to write task ('concatfiles') for getting all JavaScript files and use concat package to concat them and write it to destination folder which we have created.
    JavaScript
    // Task Name [concatfiles]
    gulp.task('concatfiles', function ()
    {   // path to your files
         gulp.src(paths.js)
        // concat files
        .pipe(concat(newconcat))
        // Writing files to Destination
        .pipe(gulp.dest(paths.Destination));
    });
  7. In the seventh step, we are going to write Main task such that we can run another task sequentially
    JavaScript
    gulp.task("demo", ["concatfiles"]);

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

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

Snapshot of Task Runner Explorer

Image 32

After running task, we have to see "ConcatenatedJsfiles" folder where concatenated JavaScript file is stored.

Folder Structure

Image 33

Output of Concatenated JavaScript Files

Image 34

Step 9: Writing Task to Minify JavaScript

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

Folder Structure

Image 35

JavaScript File to Minify

Image 36

Complete Code Snippet of gulpfile.js

JavaScript
var gulp = require('gulp');

//Using package to minifying files 
uglify = require("gulp-uglify");

var paths = {
    webroot: "./wwwroot/"
};

//Getting Path of Javascript files 
paths.js = paths.webroot + "js/**/*.js";

//Path to Writing minified Files after minifying
paths.Destination = paths.webroot + "MinifiedJavascriptfiles";

// Task Name [MinifyingTask]
gulp.task('MinifyingTask', function () {   // path to your files
    gulp.src(paths.js)
   // concat files
   .pipe(uglify())
   // Writing files to Destination
   .pipe(gulp.dest(paths.Destination));
});

Understanding Code Snippet of gulpfile.js

  1. In the first step, we are going to load module.
    JavaScript
    var gulp = require('gulp');
    
    //Using package to minifying files 
    uglify = require("gulp-uglify");
  2. In the second step, we are going to declare variable with name "paths" which is going to store the path of "wwwroot".
    JavaScript
    var paths = {
        webroot: "./wwwroot/"
    };
  3. In the third step, we are going declare path to get JavaScript files from folder "Js" folder.
    JavaScript
    //Getting Path of Javascript files 
    paths.js = paths.webroot + "js/**/*.js";
  4. In the fourth step, we are going to declare the path to store minified files in "MinifiedJavascriptfiles" folder after minifying.
    JavaScript
    //Path to Writing minified Files after minifying
    paths.Destination = paths.webroot + "MinifiedJavascriptfiles";
  5. In the fifth step, we are going to write task (‘MinifyingTask’) for getting all JavaScript files and use uglify package to minify JavaScript files and then write it to destination folder which we have created.
    JavaScript
    // Task Name [MinifyingTask]
    gulp.task('MinifyingTask', function () 
    {   // path to your files
        gulp.src(paths.js)
       // concat files
       .pipe(uglify())
       // Writing files to Destination
       .pipe(gulp.dest(paths.Destination));
    });

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

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

Snapshot of Task Runner Explorer

Image 37

After running task, we have to see "MinifiedJavascriptfiles" folder where minified JavaScript file is stored.

Folder Structure

Image 38

Output of Minified JavaScript Files

Image 39

Step 10: Writing Task to Minify Cascading Style Sheets

In this step, we are going to write a task for minifying cascading style sheets files. To do that, first I am going to add a folder with name MinifiedCssfiles in the 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 the "css" folder for minifying.

Image 40

Cascading Style Sheets File to Minify

Image 41

Complete Code Snippet of gulpfile.js

JavaScript
var gulp = require('gulp');

//Using package to minifying css files 
cssmin = require("gulp-cssmin");
        
var paths = {
    webroot: "./wwwroot/"
};

//Getting Path of Javascript files 
paths.css = paths.webroot + "css/**/*.css";

//Path to Writing minified Files after minifying
paths.Destination = paths.webroot + "MinifiedCssfiles";

// Task Name [MinifyingTask]
gulp.task('Minifying-Css-Task', function () {   // path to your files
    gulp.src(paths.css)
   .pipe(cssmin())
   // Writing files to Destination
   .pipe(gulp.dest(paths.Destination));
});

Understanding Code Snippet of gulpfile.js

  1. In the first step, we are going to load module.
    JavaScript
    var gulp = require('gulp');
    
    //Using package to minifying css files 
    cssmin = require("gulp-cssmin");
  2. In the second step, we are going to declare variable with name "paths" which is going to store the path of "wwwroot".
    JavaScript
    var paths = {
        webroot: "./wwwroot/"
    };
  3. In the third step, we are going to declare path to get JavaScript files from folder "css" folder.
    JavaScript
    //Getting Path of cascading style sheets files 
    paths.css = paths.webroot + "css/**/*.css";
  4. In the fourth step, we are going to declare the path to store minified files in "MinifiedCssfiles" folder after minifying.
    JavaScript
    //Path to Writing minified Files after minifying
    paths.Destination = paths.webroot + "MinifiedCssfiles";
  5. In the fifth step, we are going to write task (‘Minifying-Css-Task’) for getting all Cascading style sheets files and use cssmin package to minify Cascading style sheets files and then write it to destination folder which we have created.
    JavaScript
    // Task Name [Minifying-Css-Task]
    gulp.task('Minifying-Css-Task', function () {   // path to your files
        gulp.src(paths.css)
       .pipe(cssmin())
       // Writing files to Destination
       .pipe(gulp.dest(paths.Destination));
    });

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

To run, just right click on "Minifying-Css-Task" and from the list of menu, choose Run menu.

Snapshot of Task Runner Explorer

Image 42

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

Image 43

Output of Minified JavaScript Files

Image 44

Note: Syntax if you want to run more than one task sequentially

Step 11: Writing Task to Change File Extension of JavaScript Files and Cascading Style Sheet

In this step, we are going to write a task for changing extension of cascading style sheets file and JavaScript files. To do that, first I am going to add a folder with the name Changedextensionfiles in wwwroot folder. In this folder, all changing extension of cascading style sheets file and JavaScript file will be stored.

And we are going to get cascading style sheets file from the "css" folder and the JavaScript files from the "js" folder.

Folder Structure

Image 45

Complete Code Snippet of gulpfile.js

JavaScript
var gulp = require('gulp');

//Using package to minifying files 
ext_replace = require("gulp-ext-replace");

var paths = {webroot: "./wwwroot/"};

//Getting Path of Javascript files 
paths.js = paths.webroot + "js/**/*.js";

//Getting Path of cascading style sheets files 
paths.css = paths.webroot + "css/**/*.css";

//Path to Writing Changed extensions files
paths.Destination = paths.webroot + "Changedextensionfiles";

// Task Name [Changing Extension Javascript]
gulp.task('ChangingExtensionJavascriptTask', function () {
    // path to your files
    gulp.src(paths.js)
    // change file extension from .js to .min.js
    .pipe(ext_replace('.min.js'))
    // Writing files to Destination
    .pipe(gulp.dest(paths.Destination));
});

// Task Name [Changing Extension Css]
gulp.task('ChangingExtensionCssTask', function () {
    // path to your files
    gulp.src(paths.css)
    // change file extenstion from css to .min.css
    .pipe(ext_replace('.min.css'))
    // Writing files to Destination
    .pipe(gulp.dest(paths.Destination));
});

//Syntax If you want to run more than one task sequentially
gulp.task("MainTask", ["ChangingExtensionJavascriptTask", "ChangingExtensionCssTask"]);

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

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

Snapshot of Task Runner Explorer

Image 46

After running task, we have to see "Changedextensionfiles" folder where changed cascading style sheets file and JavaScript file will be stored.

Snapshot After Changing File Extension

Image 47

Step 12: Automating Task

To automate this process, just right click on Bindings from the list, you will find four items in it.

Choose Bindings according to your need to automate the process.

Image 48

Image 49

As you choose, this binding is added to gulpfile.js as shown below.

Image 50

In this article, we have learned how to use gulp with ASP.NET Core MVC and along with this how to install "Task Runner Explorer" and how to minify and beautify JavaScript, cascading style sheets, and HTML.

I hope you liked my article.

History

  • 10th January, 2017: Initial version

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

 
PraiseThanks Pin
alvinchesaro17-Oct-19 3:41
professionalalvinchesaro17-Oct-19 3:41 
QuestionWhat is the difference between gulp and grunt Pin
Mou_kol18-Aug-17 0:45
MemberMou_kol18-Aug-17 0:45 
GeneralMy vote of 4 Pin
Klaus Luedenscheidt10-Jan-17 19:40
MemberKlaus Luedenscheidt10-Jan-17 19:40 
GeneralRe: My vote of 4 Pin
Saineshwar Bageri10-Jan-17 21:26
Member Saineshwar Bageri10-Jan-17 21:26 
GeneralRe: My vote of 4 Pin
Klaus Luedenscheidt10-Jan-17 23:00
MemberKlaus Luedenscheidt10-Jan-17 23:00 
GeneralRe: My vote of 4 Pin
Saineshwar Bageri10-Jan-17 23:21
Member Saineshwar Bageri10-Jan-17 23:21 

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.