Search code examples
angulartypescriptgulpbrowser-sync

Gulp BrowserSync with typescript and angular 2


I'm trying to get browserSync to work with a typescript compiler and angular. When I change something in my app.ts, it recompiles properly, and browsersync prints "Reloading Browsers..." but the browser never actually reloads. I can't seem to figure out why it's not reloading, perhaps it has something to do with the way Angular 2 handles refreshes?

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var tsc = require('gulp-typescript');
var tsProject = tsc.createProject('tsconfig.json');
var config = require('./gulp.config')();
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;

// Start a local server in base directory
gulp.task('serve', function() {
    browserSync.init({
        server: {
            baseDir: './'
        }
    });

    // Watch for changes in html and ts files in base directory, reload if they occur
    gulp.watch(['*.html', '*.ts'], ['reloady']);

    // Watches for changes in css files, grabs the files, pipes them to browsersync stream
    // This injects the css into the page without a reload
    gulp.watch('*.css', function() {
        gulp.src('*css')
            .pipe(browserSync.stream());
    });
});

gulp.task('compile-ts', function() {
    var sourceTsFiles = [
        config.allTs,
        config.typings
    ];

    var tsResult = gulp
        .src(sourceTsFiles)
        .pipe(sourcemaps.init())
        .pipe(tsc(tsProject));

    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.tsOutputPath))
});

gulp.task('reloady', ['compile-ts'], function() {
    console.log("Reload SHOULD have happened.");
    browserSync.reload();
});

Edit: Solved! In order for Browsersync to connect properly the body tag must be present in your website (we add a script tag just after it). See my answer below for details.


Solution

  • Well I've finally figured it out, the answer turns out to be simple, as these things go.

    I was just starting out with Angular 2 so I made a quick little hello world, and the files get served up with browsersync just fine, and I could manually reload it. However, when browsersync.reload() was called, it wasn't doing anything. In the help/about section of the browsersync UI, it says the following:

    Why isn’t Browsersync connecting with my project? 99% of the time, it's because your web page doesn't have a body tag. In order for Browsersync to connect properly the body tag must be present in your website (we add a script tag just after it).

    In my quick creation of the html for the hello world app, I never put body tags in. Problem solved!