This quick start guide will teach you how to build TypeScript with gulp and then add Browserify, uglify, or Watchify to the gulp pipeline. This guide also shows how to add Babel functionality using Babelify.

We assume that you’re already using Node.js with npm.

Minimal project

Let’s start out with a new directory. We’ll name it proj for now, but you can change it to whatever you want.

  1. mkdir proj
  2. cd proj

To start, we’re going to structure our project in the following way:

  1. proj/
  2. ├─ src/
  3. └─ dist/

TypeScript files will start out in your src folder, run through the TypeScript compiler and end up in dist.

Let’s scaffold this out:

  1. mkdir src
  2. mkdir dist

Initialize the project

Now we’ll turn this folder into an npm package.

  1. npm init

You’ll be given a series of prompts. You can use the defaults except for your entry point. For your entry point, use ./dist/main.js. You can always go back and change these in the package.json file that’s been generated for you.

Install our dependencies

Now we can use npm install to install packages. First install gulp-cli globally (if you use a Unix system, you may need to prefix the npm install commands in this guide with sudo).

  1. npm install -g gulp-cli

Then install typescript, gulp and gulp-typescript in your project’s dev dependencies. Gulp-typescript is a gulp plugin for TypeScript.

  1. npm install --save-dev typescript gulp@4.0.0 gulp-typescript

Write a simple example

Let’s write a Hello World program. In src, create the file main.ts:

  1. function hello(compiler: string) {
  2. console.log(`Hello from ${compiler}`);
  3. }
  4. hello("TypeScript");

In the project root, proj, create the file tsconfig.json:

  1. {
  2. "files": ["src/main.ts"],
  3. "compilerOptions": {
  4. "noImplicitAny": true,
  5. "target": "es5"
  6. }
  7. }

Create a gulpfile.js

In the project root, create the file gulpfile.js:

  1. var gulp = require("gulp");
  2. var ts = require("gulp-typescript");
  3. var tsProject = ts.createProject("tsconfig.json");
  4. gulp.task("default", function() {
  5. return tsProject
  6. .src()
  7. .pipe(tsProject())
  8. .js.pipe(gulp.dest("dist"));
  9. });

Test the resulting app

  1. gulp
  2. node dist/main.js

The program should print “Hello from TypeScript!“.

Add modules to the code

Before we get to Browserify, let’s build our code out and add modules to the mix. This is the structure you’re more likely to use for a real app.

Create a file called src/greet.ts:

  1. export function sayHello(name: string) {
  2. return `Hello from ${name}`;
  3. }

Now change the code in src/main.ts to import sayHello from greet.ts:

  1. import { sayHello } from "./greet";
  2. console.log(sayHello("TypeScript"));

Finally, add src/greet.ts to tsconfig.json:

  1. {
  2. "files": ["src/main.ts", "src/greet.ts"],
  3. "compilerOptions": {
  4. "noImplicitAny": true,
  5. "target": "es5"
  6. }
  7. }

Make sure that the modules work by running gulp and then testing in Node:

  1. gulp
  2. node dist/main.js

Notice that even though we used ES2015 module syntax, TypeScript emitted CommonJS modules that Node uses. We’ll stick with CommonJS for this tutorial, but you could set module in the options object to change this.

Browserify

Now let’s move this project from Node to the browser. To do this, we’d like to bundle all our modules into one JavaScript file. Fortunately, that’s exactly what Browserify does. Even better, it lets us use the CommonJS module system used by Node, which is the default TypeScript emit. That means our TypeScript and Node setup will transfer to the browser basically unchanged.

First, install browserify, tsify, and vinyl-source-stream. tsify is a Browserify plugin that, like gulp-typescript, gives access to the TypeScript compiler. vinyl-source-stream lets us adapt the file output of Browserify back into a format that gulp understands called vinyl.

  1. npm install --save-dev browserify tsify vinyl-source-stream

Create a page

Create a file in src named index.html:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Hello World!</title>
  6. </head>
  7. <body>
  8. <p id="greeting">Loading ...</p>
  9. <script src="bundle.js"></script>
  10. </body>
  11. </html>

Now change main.ts to update the page:

  1. import { sayHello } from "./greet";
  2. function showHello(divName: string, name: string) {
  3. const elt = document.getElementById(divName);
  4. elt.innerText = sayHello(name);
  5. }
  6. showHello("greeting", "TypeScript");

Calling showHello calls sayHello to change the paragraph’s text. Now change your gulpfile to the following:

  1. var gulp = require("gulp");
  2. var browserify = require("browserify");
  3. var source = require("vinyl-source-stream");
  4. var tsify = require("tsify");
  5. var paths = {
  6. pages: ["src/*.html"]
  7. };
  8. gulp.task("copy-html", function() {
  9. return gulp.src(paths.pages).pipe(gulp.dest("dist"));
  10. });
  11. gulp.task(
  12. "default",
  13. gulp.series(gulp.parallel("copy-html"), function() {
  14. return browserify({
  15. basedir: ".",
  16. debug: true,
  17. entries: ["src/main.ts"],
  18. cache: {},
  19. packageCache: {}
  20. })
  21. .plugin(tsify)
  22. .bundle()
  23. .pipe(source("bundle.js"))
  24. .pipe(gulp.dest("dist"));
  25. })
  26. );

This adds the copy-html task and adds it as a dependency of default. That means any time default is run, copy-html has to run first. We’ve also changed default to call Browserify with the tsify plugin instead of gulp-typescript. Conveniently, they both allow us to pass the same options object to the TypeScript compiler.

After calling bundle we use source (our alias for vinyl-source-stream) to name our output bundle bundle.js.

Test the page by running gulp and then opening dist/index.html in a browser. You should see “Hello from TypeScript” on the page.

Notice that we specified debug: true to Browserify. This causes tsify to emit source maps inside the bundled JavaScript file. Source maps let you debug your original TypeScript code in the browser instead of the bundled JavaScript. You can test that source maps are working by opening the debugger for your browser and putting a breakpoint inside main.ts. When you refresh the page the breakpoint should pause the page and let you debug greet.ts.

Watchify, Babel, and Uglify

Now that we are bundling our code with Browserify and tsify, we can add various features to our build with browserify plugins.

  • Watchify starts gulp and keeps it running, incrementally compiling whenever you save a file. This lets you keep an edit-save-refresh cycle going in the browser.
  • Babel is a hugely flexible compiler that converts ES2015 and beyond into ES5 and ES3. This lets you add extensive and customized transformations that TypeScript doesn’t support.
  • Uglify compacts your code so that it takes less time to download.

Watchify

We’ll start with Watchify to provide background compilation:

  1. npm install --save-dev watchify fancy-log

Now change your gulpfile to the following:

  1. var gulp = require("gulp");
  2. var browserify = require("browserify");
  3. var source = require("vinyl-source-stream");
  4. var watchify = require("watchify");
  5. var tsify = require("tsify");
  6. var fancy_log = require("fancy-log");
  7. var paths = {
  8. pages: ["src/*.html"]
  9. };
  10. var watchedBrowserify = watchify(
  11. browserify({
  12. basedir: ".",
  13. debug: true,
  14. entries: ["src/main.ts"],
  15. cache: {},
  16. packageCache: {}
  17. }).plugin(tsify)
  18. );
  19. gulp.task("copy-html", function() {
  20. return gulp.src(paths.pages).pipe(gulp.dest("dist"));
  21. });
  22. function bundle() {
  23. return watchedBrowserify
  24. .bundle()
  25. .on("error", fancy_log)
  26. .pipe(source("bundle.js"))
  27. .pipe(gulp.dest("dist"));
  28. }
  29. gulp.task("default", gulp.series(gulp.parallel("copy-html"), bundle));
  30. watchedBrowserify.on("update", bundle);
  31. watchedBrowserify.on("log", fancy_log);

There are basically three changes here, but they require you to refactor your code a bit.

  1. We wrapped our browserify instance in a call to watchify, and then held on to the result.
  2. We called watchedBrowserify.on('update', bundle); so that Browserify will run the bundle function every time one of your TypeScript files changes.
  3. We called watchedBrowserify.on('log', fancy_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:

  1. proj$ gulp
  2. [10:34:20] Using gulpfile ~/src/proj/gulpfile.js
  3. [10:34:20] Starting 'copy-html'...
  4. [10:34:20] Finished 'copy-html' after 26 ms
  5. [10:34:20] Starting 'default'...
  6. [10:34:21] 2824 bytes written (0.13 seconds)
  7. [10:34:21] Finished 'default' after 1.36 s
  8. [10:35:22] 2261 bytes written (0.02 seconds)
  9. [10:35:24] 2808 bytes written (0.05 seconds)

Uglify

First install Uglify. Since the point of Uglify is to mangle your code, we also need to install vinyl-buffer and gulp-sourcemaps to keep sourcemaps working.

  1. npm install --save-dev gulp-uglify vinyl-buffer gulp-sourcemaps

Now change your gulpfile to the following:

  1. var gulp = require("gulp");
  2. var browserify = require("browserify");
  3. var source = require("vinyl-source-stream");
  4. var tsify = require("tsify");
  5. var uglify = require("gulp-uglify");
  6. var sourcemaps = require("gulp-sourcemaps");
  7. var buffer = require("vinyl-buffer");
  8. var paths = {
  9. pages: ["src/*.html"]
  10. };
  11. gulp.task("copy-html", function() {
  12. return gulp.src(paths.pages).pipe(gulp.dest("dist"));
  13. });
  14. gulp.task(
  15. "default",
  16. gulp.series(gulp.parallel("copy-html"), function() {
  17. return browserify({
  18. basedir: ".",
  19. debug: true,
  20. entries: ["src/main.ts"],
  21. cache: {},
  22. packageCache: {}
  23. })
  24. .plugin(tsify)
  25. .bundle()
  26. .pipe(source("bundle.js"))
  27. .pipe(buffer())
  28. .pipe(sourcemaps.init({ loadMaps: true }))
  29. .pipe(uglify())
  30. .pipe(sourcemaps.write("./"))
  31. .pipe(gulp.dest("dist"));
  32. })
  33. );

Notice that uglify itself has just one call — the calls to buffer and sourcemaps exist to make sure sourcemaps keep working. These calls give us a separate sourcemap file instead of using inline sourcemaps like before. Now you can run Gulp and check that bundle.js does get minified into an unreadable mess:

  1. gulp
  2. cat dist/bundle.js

Babel

First install Babelify and the Babel preset for ES2015. Like Uglify, Babelify mangles code, so we’ll need vinyl-buffer and gulp-sourcemaps. By default Babelify will only process files with extensions of .js, .es, .es6 and .jsx so we need to add the .ts extension as an option to Babelify.

  1. npm install --save-dev babelify@8 babel-core babel-preset-es2015 vinyl-buffer gulp-sourcemaps

Now change your gulpfile to the following:

  1. var gulp = require("gulp");
  2. var browserify = require("browserify");
  3. var source = require("vinyl-source-stream");
  4. var tsify = require("tsify");
  5. var sourcemaps = require("gulp-sourcemaps");
  6. var buffer = require("vinyl-buffer");
  7. var paths = {
  8. pages: ["src/*.html"]
  9. };
  10. gulp.task("copy-html", function() {
  11. return gulp.src(paths.pages).pipe(gulp.dest("dist"));
  12. });
  13. gulp.task(
  14. "default",
  15. gulp.series(gulp.parallel("copy-html"), function() {
  16. return browserify({
  17. basedir: ".",
  18. debug: true,
  19. entries: ["src/main.ts"],
  20. cache: {},
  21. packageCache: {}
  22. })
  23. .plugin(tsify)
  24. .transform("babelify", {
  25. presets: ["es2015"],
  26. extensions: [".ts"]
  27. })
  28. .bundle()
  29. .pipe(source("bundle.js"))
  30. .pipe(buffer())
  31. .pipe(sourcemaps.init({ loadMaps: true }))
  32. .pipe(sourcemaps.write("./"))
  33. .pipe(gulp.dest("dist"));
  34. })
  35. );

We also need to have TypeScript target ES2015. Babel will then produce ES5 from the ES2015 code that TypeScript emits. Let’s modify tsconfig.json:

  1. {
  2. "files": ["src/main.ts"],
  3. "compilerOptions": {
  4. "noImplicitAny": true,
  5. "target": "es2015"
  6. }
  7. }

Babel’s ES5 output should be very similar to TypeScript’s output for such a simple script.