Search code examples
node.jsgulpgulp-watchbrowser-sync

Gulp: Trouble setting browserSync and Watch


I'm learning Gulp and NPM and decided to test myself by using Browser-Sync with a PHP project I'm working on (using XAMPP). I know Browser-Sync doesnt work with PHP files, but I wanted to use it with my .css files (and later on perhaps add Sass).

I installed npm, Gulp, Gulp-watch and Browser Sync to my project's root directory and all seemed fine.

I then created a gulp.js file with the following:

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

gulp.task('watch', function() {
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });

    watch('css/*.css', function() {
        browserSync.reload();
    });

});

However, when I gulp watch a new browser window does open but just shows the Cannot GET / error.

Also, the URL shows http://localhost:3002/ rather than http://localhost:myproejct

I read this may have something to do with my baseDir so tried:

baseDir: ""
baseDir: "./"
baseDir: "../myproject"

Would anyone know what I've done wrong?


Solution

  • You are doing way more than is necessary to do what you want. You can just use browsersync as a proxy layer over the top of your hosted site.

    See the following example from the docs

    # Proxy a PHP app + serve static files & watch them
    $ browser-sync start --proxy 'mylocal.dev' --serveStatic 'public' --files 'public'
    

    I think this is what you will need, run it from the physical root of your site and replace mylocal.dev with your php server address

    npm install browser-sync -g
    
    browser-sync start --proxy 'mylocal.dev' --serveStatic 'css' --files 'css/*.css'