Gulp – Validate JavaScript

Gulp, Gulp – Validate JavaScript

The web runs on more than HTML and CSS, It runs on JavaScript. Let’s perform some common JavaScript build operations with gulp.

We will first look into validating our JavaScript using gulp.

And yes… there is a plugin for that.

1
$ npm install gulp-jsvalidate --save-dev

For more information on gulp-jsvalidate check out https://github.com/sindresorhus/gulp-jsvalidate.

We will now create a new Javascript task in our gulpfile.js. At first, all we will do is validate our Javascript in a new /contents/javascripts folder.

/gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
...
var jsValidate = require('gulp-jsvalidate');
...

...
gulp.task('javascript', function () {
  console.log("Validate JavaScript");
  return gulp.src("contents/javascripts/**.js")
    .pipe(jsValidate());
});
...

Time to test out our new task and plugin. Create a javascript file and make a syntax error.

/contents/javascript/somejs.js
1
2
3
4
function OMG() {
  var x * 2; // this is not valid!
  return x + 10;
}

Now when we run our javascript task, we will get an error message in the terminator:

1
2
3
4
5
$ gulp javascript

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'javascript'...
'javascript' errored after 14 ms Line 3: Unexpected token *

When we fix the error and then run our gulp task, we won’t get that error message:

/contents/javascript/somejs.js
1
2
3
4
function OMG() {
  var x = 2;
  return x + 10;
}
1
2
3
4
5
6
$ gulp javascript

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'javascript'...
Validate JavaScript
Finished 'javascript' after 14 ms

Sweet codes! Gulp can now check if our JavaScript is valid. But the error message in the console is rather bland, lets find a better way to tell us that we messed up.