jmccole83
5/30/2018 - 6:45 PM

Setup Gulp and BrowserSync locally manually

Instructions on how to setup Gulp and BrowserSync manually.

// Include gulp
var gulp = require('gulp');
// Include BrowserSync
var browserSync = require('browser-sync').create();

// Include Our Plugins
var jshint = require('gulp-jshint');
var sass   = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

// Create server
gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: './'
    },
  })
})

// Lint Task
gulp.task('lint', function() {
    return gulp.src('js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(browserSync.reload({
          stream: true
        }));
});

// Compile Our Sass
gulp.task('sass', function() {
    return gulp.src('sass/*.sass')
        .pipe(sass())
        .pipe(gulp.dest('dist/css'))
        .pipe(browserSync.reload({
          stream: true
        }));
});

// Concatenate & Minify JS
gulp.task('scripts', function() {
    return gulp.src('js/*.js')
        .pipe(concat('main.js'))
        .pipe(gulp.dest('dist/js'))
        .pipe(rename('main.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'))
        .pipe(browserSync.reload({
          stream: true
        }));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('js/*.js', ['lint', 'scripts'], browserSync.reload);
    gulp.watch('sass/*.sass', ['sass'], browserSync.reload);
    gulp.watch('*.html', browserSync.reload);
});

// Default Task
gulp.task('default', ['lint', 'sass', 'scripts', 'watch', 'browserSync']);
Install Gulp globally (if not already installed):

$ npm install gulp -g

Navigate to the project directory, run npm init to setup the project:

$ npm init

Install Gulp to the project:

$ npm install gulp --save-dev

Install BrowserSync:

$ npm install -g browser-sync

Install JS-Hint:

$ npm install jshint gulp-jshint --save-dev

Create the file gulpfile.js, enter the below snippet and save.

Run 'gulp' from the terminal.

Example below assumes this project hierarchy:

./
gulpfile.js
index.html
package.json
package-lock.json
/dist
  /css
  main.css
  /js
  main.min.js
/js
  main.js
/node_modules
/sass
  main.sass
  
Customise the files being watched as needed, e.g. gulp.watch('*.php', browserSync.reload);