How to automatically update on localhost after editing files

Use Gulp + Gulp-Watch + BrowserSync.

The goal is to run an extra process that monitors any changes in your files. When a change occurs the page is automatically reloaded including CSS injection / Scrolls / Browser clicks and all concurrently across multiple devices and browsers. Because it also generates an ip:port you can access the link from other devices in your network.

This gulpfile.js task is based on the roots.ioSage theme.


var $           = require('gulp-load-plugins')();
var gulp        = require('gulp');
var browserSync = require('browser-sync');

gulp.task('watch-local.dev', function() { 
  init_watch ( false, 3001, { target: 'http://local.dev' } ); 
});

This breakout function allows you to create tasks per environment including; MAMP, WAMP, Docker and Vagrant & toggle http / https individually. Note: local.dev is a byproduct of Vagrant Host Manager.

function init_watch (https, port, proxy) {

    var defaults = {
        port: 3001,
        https: true,
        proxy: config.devUrl // { target: 'http://your-expected-site-name.com' }
    };

    if( typeof https !== 'boolean') { https = defaults.https; }
    if( typeof port !== 'number') { port = defaults.port; }
    if( typeof proxy === 'string') { proxy = { target: proxy }; } // fix the format if only target is passed
    if( typeof proxy !== 'object') { proxy = defaults.proxy; }

    browserSync({
        proxy: proxy,
        https: https,
        port: port,
        snippetOptions: {
            whitelist: ['/wp-admin/admin-ajax.php'],
            blacklist: ['/wp-admin/**']
        }
    });

    gulp.watch([path.source + 'styles/**/*'], ['styles']);
    gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
    gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
    gulp.watch([path.source + 'images/**/*'], ['images']);
    gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
    gulp.watch('**/*.php', function() {
        browserSync.reload();
    });
}

To execute this task you’ll need to run the following command. There are also ways to initiate the gulp task from an IDE including; PHPStorm / WebStorm, Atom.io and Sublime.

gulp watch-local.dev

It’s worth mentioning that the proxy generally works well unless you’re browsing the admin portion of your site.

You’ll also need Node.js and the npm command-line tool is bundled with it.

If you need to deploy the content you can add a task to FTP files on change.

Leave a Comment