Gulp: Running a local server with Tiny LiveReload 7/30/14
This is my Gulp
The plugins we’ll need
- gulp-webserver — Runs the local webserver and sets up Tiny LiveReload
- gulp-sass — Compiles SCSS into CSS files
- gulp-plumber — Keeps Gulp watch from dying when one of the tasks has an error
- Node opn — Opens your browser to view the webserver
Installing the plugins
Assuming you have Node and Gulp installed, navigate to your project folder in the terminal and run this command to install the plugins
npm install gulp-webserver gulp-sass gulp-sass gulp-plumber opn
Create your project files
Our example gulpfile.js
expects a basic project structure. We have an index.html
and gulpfile.js
file in our root, a scss
folder for our styles.scss
source file, and a css
folder for our compiled SCSS:
Go ahead and put some actual SCSS into styles.scss
and HTML into index.html
.
The gulpfile.js
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sass = require('gulp-sass');
var webserver = require('gulp-webserver');
var opn = require('opn');
var sourcePaths = {
styles: ['scss/**/*.scss']
};
var distPaths = {
styles: 'css'
};
var server = {
host: 'localhost',
port: '8001'
}
gulp.task('sass', function () {
gulp.src( sourcePaths.styles )
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest( distPaths.styles ));
});
gulp.task('webserver', function() {
gulp.src( '.' )
.pipe(webserver({
host: server.host,
port: server.port,
livereload: true,
directoryListing: false
}));
});
gulp.task('openbrowser', function() {
opn( 'http://' + server.host + ':' + server.port );
});
gulp.task('watch', function(){
gulp.watch(sourcePaths.styles, ['sass']);
});
gulp.task('build', ['sass']);
gulp.task('default', ['build', 'webserver', 'watch', 'openbrowser']);
Running gulp
If you’ve done everything right up to this point, you should be able to run gulp
styles.scss
and watch the browser reload the stylesheet automatically.
You can download a complete example project from Github.
-
A few months back I joked about dropping Grunt in favor of Gulp, and now I have. The syntax is significantly more understandble. ↩
-
Adding
--save-dev
to the end of the npm install command will add your new modules to the package.json file in your project. ↩ -
Running
gulp
without any options calls thedefault
task we defined at the end of the gulpfile. ↩