Categories
Samuel Sass

Setting Up WordPress with Sass and Browser Sync

This post is mainly a helpful reminder reference to my future self so please excuse the lack of polish on this article.

Outline:

  • Create a package.json file with all the needed dependencies to get Sass + Browser sync working
  • Install all dependencies using NPM
  • Activate Gulp Watch + Browser-sync to enjoy lighting fast developing

Creating Json File:

Initially its best to create this file from the command line, so open terminal in php storm, navigate to the sites theme file and run the npm commands, which will generate this file:

{
  "name": "SassAutomation",
  "version": "0.0.1",
  "description": "Quick & dirty SASS automation for WP Theme",
  "author": "Sam",
  "devDependencies": {
    "gulp": "^3.8.11",
    "browser-sync": "^2.26.7",
    "gulp-ruby-sass": "^1.0.5",
    "gulp-sass": "^4.0.2",
    "gulp-sourcemaps": "^1.5.2",
    "gulp-watch": "^5.0.1",
    "node-sass": "^4.12.0",
  }
}

Setup Gulp File:

We want to create a gulpfile that will watch all of our Sass files for changes. When a change is detected we want this file to re-compile the new sass into our sites main style.css file located in the root directory of the them. The Gulp file below will do all of these operations:

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    watch = require('gulp-watch');
    browserSync = require('browser-sync');
    reload      = browserSync.reload;

gulp.task('sass', function(){
    gulp.src('./scss/style.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(''))
        .pipe(reload({stream:true}));
});

// browser-sync task for starting the server.
gulp.task('browser-sync', function() {
    //watch files
    var files = [
        './scss/*.scss',
    ];

    //initialize browsersync
    browserSync.init(files, {
        //browsersync with a php server
        proxy: "http://localhost/folder-name",
        notify: true
    });
});

gulp.task('default', ['sass', 'browser-sync'], function() {
    gulp.watch('./scss/**/*.scss', ['sass']);
});

Notes about the code above:

  • Line 4 calls in browser sync which will open a new window when you run the gulp command
  • Line 5 and line 10 forces the auto refresh of the browser window anytime a change is made, which is super handy as it removes the need to constantly manually refresh the local environment to see our chagnes
  • The line that starts with “proxy” identifies where the site should display. In this instance I’m using WAMP which generates a URL of localhost. The “folder-name” at the end of the line can be replaced with whatever folder the site lives in. So IE if the site was in WAMP – > WWW -> altec the proxy line would be: http://localhost/altec