Tuesday, January 5, 2016

Using JSHint with an ASP.NET 5 Web Application

JSHint is one of the most popular JavaScript Code Quality Tools which is widely been used among the JavaScript developers. In this post let’s see how we can use JSHint with an ASP.NET 5 application using Visual Studio 2015.

First let’s create an ASP.NET 5 Web Application.
image
ASP.NET 5 Web Application.
Then from the Solution Explorer, under the project, expand “Dependencies” node. Right click on “npm” folder and open up the package.json file.
image
Open package.json
Add the “gulp-jshint” devDependency as follows (last line).
{
  "name": "ASP.NET",
  "version": "0.0.0",
  "devDependencies": {
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8",
    "gulp-jshint": "2.0.0"
  }
}
Upon saving of the file, you will notice that relevant packages are getting downloaded/restored.

Next step is to modify the gulpfile.js and add a new task to run JSHint.

For that Open up the gulpfile.js and include the “gulp-jshint” plugin as follows (last line).
var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    jshint = require("gulp-jshint");
And then add a new gulp task to run the JSHint.
gulp.task('jshint', function () {
    gulp.src("./wwwroot/" + "js/**/*.js")
      .pipe(jshint())
      .pipe(jshint.reporter('default'));
});
Now that is it. Open up the Task Runner Explorer and you should be able to see the new jshint task you have just created.
image
Task Runner Explorer
For testing the task, first let’s add some JavaScript codes to js files where the jshint task is watching. We have mentioned that jshint task is watching .js files inside wwwroot/js folder. In the default ASP.NET 5 project template there is a file named site.js, we can easily modify that.

I am adding following code there and you might notice that there are couple of issues with the code.
// Write your Javascript code.
 
"use strict";
 
function sayHello() {
    return 'Hello World!';
}
 
sayHello()
 
sayHelloWorld();
To find out what are those, from the Task Runner Explorer let’s run the jshint task.
image
Task Runner Explorer
image
Task Runner Explorer
As you can see jshint is showing up the list of issues. Even we can bind the task to run once the project is built.
image
Task Runner Explorer
So when the project is built, you will see the list of issues (if any) in the Task Runner Explorer. So now you can start fixing those.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment