I love when a great set of tools gets an update; especially when it’s an improvement on overall functionality, and ease of use. Not to mention one that dramatically decreases weight of file size on disk for shared projects. A good case in point and the selected topic for this article today is the Gulp-Webserver plugin for the Gulp task runner software.
The Gulp-Webserver plugin is exactly what it sounds like, but unlike previous methods to set up and run a localized server and development environment with Gulp, it combines many useful concepts into one compact plugin. In the past, this would require an array of plugins to manage a lot of specific services such as Gulp-Connect, Gulp-Serve, Gulp-watch, Gulp-Livereload, and Gulp-Open; to name a few. With Gulp-Webserver we can easily replace all of these plugins and drastically simplify our code.
The GulpFile.js
First we require Gulp and Gulp-Webserver like this:
var gulp = require(‘gulp’); var webserver = require(‘gulp-webserver’);
Next we create our gulp task with a simple configuration array.
gulp.task(‘webserver’, function(){ gulp.src('.') .pipe(webserver({ livereload: true, open: true })); });
Now as you can see with even the most basic configuration we have already eliminated the need for the Gulp-livereload and Gulp-Open plugins. Now let’s look at a more advanced setup where we will utilize the Livereload filter parameters.
Advanced Example
This time we will alternatively set an array for the livereload parameter where we will be able to use the filter method to watch only certain files within the project, as opposed to everything.
gulp.task(‘webserver’,function(){ gulp.src('.').pipe(webserver({ livereload: { enable: true, filter: function(fileName) { if (fileName.match(/.css$/)) { return true; } else { return false; } }, directoryListing: true, open: true } })); });
We now can watch for whenever a change has been made to any CSS document in the project and automatically refresh the display in our browser. This time we have also included the “directoryListing” option to show all files in the project folder. Another useful function is to define the fallback option. This allows us to open a specific file as the main content rather than the default index.html.
gulp.task('webserver', function() { gulp.src('.') .pipe(webserver({ fallback:'index.html' })); });
Extending Everything
Gulp-webserver goes above and beyond any other livereload / server Gulp plugin combo by adding even more built-in functionality with HTTPS, Proxies, and Middleware support. I won’t be going into all of that now so I implore you to check out the Gulp-webserver plugin yourself.