Getting started with Webpack: TypeScript

If you're starting a new web project these days, someone on your team is probably pushing for Webpack and TypeScript. Let's kick off with a little what's what.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

Webpack is an open-source JavaScript module bundler.

Did you know that TypeScript can prevent about 15% of the bugs that end up in committed code? source

For this guide we'll be using Node v8.5, NPM v5.3, TypeScript v2.5, and Webpack v3.5. The following commands will tell you which versions you have installed. If they are not exact they may still work. TypeScript and Webpack will be installed a little further on.

$ node --version
v8.5.0
$ npm --version
5.3.0

Once you have the basic dependancies all setup let's get the app directory going. Create a directory pickle (because Instagram for pickles is going to be all the new rage). You'll also want to make the basic HTML, TS, and JS files.

CODE! We need some! Fill out index.html and index.ts with the following:

<!DOCTYPE html><html><head><metacharset="utf-8"><title>Pickle</title></head><body><h1>Welcome to Pickle</h1><labelfor="color-picker">Select a new background color</label><inputid="color-picker"type="color"value="#2196F3"><script defersrc="dist/bundle.js"></script></body></html>

classPickle{constructor(privatepicker:Element,privatebackground:HTMLElement){picker.addEventListener('change',this.colorChange.bind(this),false);this.background=background;}colorChange(event:Event):void{// `<HTMLInputElement>` tells TypeScript what type `target` is so that it knows there is a `value` property available.letinput=<HTMLInputElement>event.target;this.background.style.backgroundColor=input.value;}}letpicker=document.querySelector('#color-picker');// The if avoids TypeScript complaining that `picker` might be null.if(picker){newPickle(picker,document.body);}

You can now go to http://127.0.0.1:8080 in a browser to view the end result. You should see something like this:

Note that if you make changes to index.ts you will have to run npm run build again before it'll be available in the browser. Next time we'll go over some improvements that'll make the development flow nicer. Check out TypeScript in 5 minutes for a quick intro to TypeScript.

The color<input> tag is not supported in all browsers so you may need to try a different one if something's not working.