TypeScript and Gulp
TypeScript
TypeScript is superset of JavaScript that compiles to plain JavaScript powered by Microsoft.
So far, no browser supports TypeScript directly. We need to compile typescript and use it as javascript.
TypeScript compiler make typescript file as javascript.
TypeScript has type, class, inerface, it’s similar with Java, C# etc…
Preparation
Please install following
- node
- Typescript
About node, please check other web
To install typescript
npm install typescript -g
You can use tsc command to compile .ts file.
Gulp
TypeScript has nice tutorial with gulp.
If you are not familiar with gulp, please read my other entry Gulp Get Started
Concat and Uglify
Let’s create simple project and prepare build
I made project following.
Project |- package.json |- gulpfile.js |- src |- index.html |- gree.ts |- main.ts
I added tasks to gulp to do something.
You can customize directory structures.
main.ts includes gree.ts
main.ts
import { sayHello } from "./greet"; function showHello(divName: string, name: string) { const elt = document.getElementById(divName); elt.innerText = sayHello(name); } showHello("greeting", "Honoka Kousaka");
greet.ts
export function sayHello(name: string) { return `Hello from ${name}`; }
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello World!</title> </head> <body> <p id="greeting">Loading ...</p> <script src="bundle.js"></script> </body> </html>
HTML is quite simple. Just include bundle.js not ts file.
gulp
Install following
For concat
npm install --save-dev browserify tsify vinyl-source-stream
Use browserify, tsify, vinyl-source-stream
Resolve dependencies and create one javascript file
For Uglify
npm install --save-dev gulp-uglify vinyl-buffer gulp-sourcemaps
gulpfile.js
var gulp = require('gulp'); var browserify = require("browserify"); var source = require('vinyl-source-stream'); var tsify = require("tsify"); var uglify = require('gulp-uglify'); var sourcemaps = require('gulp-sourcemaps'); var buffer = require('vinyl-buffer'); var paths = { pages: ['src/*.html'] }; gulp.task("copy-html", function () { return gulp.src(paths.pages) .pipe(gulp.dest("dist")); }); gulp.task("build", ["copy-html"], function () { return browserify({ basedir: '.', debug: true, entries: ['src/main.ts'], cache: {}, packageCache: {} }) .plugin(tsify) .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest("dist")); });
Result
Project |-dist |- index.html |- bundle.js |- bundle.js.map
Open index.html with gulp-webserver or something. It will work.