A simple gulp setup for SASS, BrowserSync and local server

Posted by: Alex on February 13, 2018

Using gulp to help organise and control your project assets is a great tool, but trying to set up the config each time can be annoying.

guwii has created the below config (gulpfile.js) to be the best fit for the majority of starter web projects so we hope you find it useful too.
It pipes style changes through autoprefixer to help support all browsers by default, as well as utilising browser-sync and connect-sync to start you up with a simple local PHP server – with browsersync injecting all the style changes and also auto-refreshing multiple devices.

If you’re new to gulp you’ll have to create a few files (gulpfile.js and package.json) in the root of your project and then run a few terminal commands to get yourself set up.
This isn’t meant to be a full tutorial, but hopefully it can provide you with a re-usable resource for future projects—to copy-paste the bits you’ll use often:

gulpfile.js

var gulp = require('gulp'),
  autoprefixer = require('gulp-autoprefixer'),
  sourcemaps = require('gulp-sourcemaps'),
  connect = require('gulp-connect-php'),
  sass = require('gulp-ruby-sass'),
  browserSync = require('browser-sync');

var output = './css';
var autoprefixerOptions = {
  browsers: ['last 2 versions']
};
gulp.task('styles', function () {
  return sass('sass/style.scss', { style: 'compressed', sourcemap:true })
    .pipe(sourcemaps.init())
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(sourcemaps.write())
    .pipe(sourcemaps.write('maps', {
      includeContent: false,
      sourceRoot: 'source'
    }))
    .pipe(gulp.dest(output))
    .pipe(browserSync.stream({ match: '**/*.css' }));
});

gulp.task('connect-sync', function () {
  connect.server({}, function () {
    browserSync({
      proxy: '127.0.0.1:8000'
    });
  });
});

gulp.task('watch', function () {
  gulp.watch("sass/**", ['styles']);
  gulp.watch(['js/**/*.js', '*.html', '**/*.php']).on('change', browserSync.reload);
});

gulp.task('default', ['styles', 'connect-sync'], function () {
  gulp.start('watch');
});

package.json

{
  "name": "guwii gulp",
  "version": "1.0",
  "description": "guwii's quick gulp setup",
  "author": "guwii",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.24.5",
    "gulp-autoprefixer": "^5.0.0",
    "gulp-connect-php": "^1.0.3",
    "gulp-ruby-sass": "^3.0.0",
    "gulp-sourcemaps": "^2.6.4"
  },
  "dependencies": {
    "gulp": "^3.9.1"
  }
}

Finally, setting it up:

You first of all need to install node.
Then in terminal, run:

cd /your/directory/here
sudo npm install gulp -g
npm install --save-dev
gulp