Gulp-webapp running BrowserSync and PHP

I spent a while trying to work this one out, but have a working solution now. The way I solved is was to use BrowserSync as the server, and added a middleware that proxies requests if they don’t match a pattern…

Install the http-proxy package…

$ npm install --save-dev http-proxy

Add the proxy package to the top of the gulpfile.js

var httpProxy = require('http-proxy');

Add a separate php server and a proxy server before the BrowserSync…

gulp.task('php-serve', ['styles', 'fonts'], function () {
    connect.server({
        port: 9001,
        base: 'app',
        open: false
    });

    var proxy = httpProxy.createProxyServer({});

    // ...

Then add the middleware for the server to see if the request needs to be proxied…

        // ...

        server: {
            baseDir   : ['.tmp', 'app'],
            routes    : {
                '/bower_components': 'bower_components'
            },

            // THIS IS THE ADDED MIDDLEWARE
            middleware: function (req, res, next) {
                var url = req.url;

                if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
                    proxy.web(req, res, { target: 'http://127.0.0.1:9001' });
                } else {
                    next();
                }
            }
        }

        // ...

And here’s the full tasks for completeness…

gulp.task('php-serve', ['styles', 'fonts'], function () {
    connect.server({
        port: 9001,
        base: 'app',
        open: false
    });

    var proxy = httpProxy.createProxyServer({});

    browserSync({
        notify: false,
        port  : 9000,
        server: {
            baseDir   : ['.tmp', 'app'],
            routes    : {
                '/bower_components': 'bower_components'
            },
            middleware: function (req, res, next) {
                var url = req.url;

                if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
                    proxy.web(req, res, { target: 'http://127.0.0.1:9001' });
                } else {
                    next();
                }
            }
        }
    });

    // watch for changes
    gulp.watch([
        'app/*.html',
        'app/*.php',
        'app/scripts/**/*.js',
        'app/images/**/*',
        '.tmp/fonts/**/*'
    ]).on('change', reload);

    gulp.watch('app/styles/**/*.scss', ['styles']);
    gulp.watch('app/fonts/**/*', ['fonts']);
    gulp.watch('bower.json', ['wiredep', 'fonts']);
});

Hope this saves you all the time I spent working this out! :o)

Leave a Comment