Using Gulp's browser-sync with MAMP in localhost testing environment

iWillGetBetter picture iWillGetBetter · Sep 23, 2016 · Viewed 8k times · Source

I have searched around but no posts pinpointed the pitholes to avoid when using Gulp's BrowserSync with a localhost testing environment. So here is this post.

I am using gulp browser-sync, doing testing with MAMP. Right now I cannot get my browser-sync watch to work. I want to reload browser whenever I save my files.

Under MAMP settings,

  1. Apache port: 80
  2. Nginx port: 80
  3. MySQL port: 3306

gulpfile.js

var gulp = require('gulp');
var browserSync = require('browser-sync'); // create a browser sync instance.

//tasks for development
// Start browserSync server
gulp.task('browserSync', function() {
  browserSync({
    server: {
        baseDir: "app"
    },
    proxy: "localhost:8080" // can be [virtual host, sub-directory, localhost with port]
});

gulp.task('watch', ['browserSync'], function () {
  gulp.watch('app/*.{php,css,js}', browserSync.reload);
});

Since we are talking about MAMP here, my directory is in htdocs/test as shown below: enter image description here

Also, my index.php file is inside /app

I am thinking I have made mistakes on many levels but right now any combination of my solutions doesnt seem to help and Ive spent hours on this. Any suggestions?

Answer

iWillGetBetter picture iWillGetBetter · Sep 23, 2016

Finally got it to work.

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

gulp.task('default', function() {
    browserSync.init({
        proxy: "http://localhost/test/app"
    });
    gulp.watch("./app/*.php").on("change", browserSync.reload);
});

Few things to look out for that the documentation might not explicitly mention:

  1. Do not miss out .create and .init() as we are referring to an instance here.
  2. If you are using some test local server like MAMP, be careful to use 'proxy' instead of 'server'.
  3. Note the URL address I am using refers to the position of the index.php
  4. Lastly, '.on("change", browserSync.reload)' to RELOAD on CHANGE.

Hope my day spent on this saved you some time.