Watchify
We’ll start with Watchify to provide background compilation:
npm install --save-dev watchify gulp-util
Now change your gulpfile to the following:
var gulp = require("gulp"); var browserify = require("browserify"); var source = require('vinyl-source-stream'); var watchify = require("watchify"); var tsify = require("tsify"); var gutil = require("gulp-util"); var paths = { pages: ['src/*.html'] }; var watchedBrowserify = watchify(browserify({ basedir: '.', debug: true, entries: ['src/main.ts'], cache: {}, packageCache: {} }).plugin(tsify)); gulp.task("copy-html", function () { return gulp.src(paths.pages) .pipe(gulp.dest("dist")); }); function bundle() { return watchedBrowserify .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest("dist")); } gulp.task("default", ["copy-html"], bundle); watchedBrowserify.on("update", bundle); watchedBrowserify.on("log", gutil.log);
There are basically three changes here, but they require you to refactor your code a bit.
- We wrapped our
browserify
instance in a call towatchify
, and then held on to the result. - We called
watchedBrowserify.on("update", bundle);
so that Browserify will run thebundle
function every time one of your TypeScript files changes. - We called
watchedBrowserify.on("log", gutil.log);
to log to the console.
Together (1) and (2) mean that we have to move our call to browserify
out of the default
task. And we have to give the function for default
a name since both Watchify and Gulp need to call it. Adding logging with (3) is optional but very useful for debugging your setup.
Now when you run Gulp, it should start and stay running. Try changing the code for showHello
in main.ts
and saving it. You should see output that looks like this:
proj$ gulp [10:34:20] Using gulpfile ~/src/proj/gulpfile.js [10:34:20] Starting 'copy-html'... [10:34:20] Finished 'copy-html' after 26 ms [10:34:20] Starting 'default'... [10:34:21] 2824 bytes written (0.13 seconds) [10:34:21] Finished 'default' after 1.36 s [10:35:22] 2261 bytes written (0.02 seconds) [10:35:24] 2808 bytes written (0.05 seconds)
Please login to continue.