Getting started with TypeScript and React

Get started with #TypeScript and #ReactJS:  #JavaScript

  • Today I’ll show you how I’ve set up a TypeScript project from scratch that uses React, and Webpack for managing the build process.
  • This turns on a few different settings, the most notable of which are and :

    Often when you want to add TypeScript to an existing project TypeScript makes it easy by not throwing an error when you don’t declare the types of variables.

  • If you run Webpack now against this code you’ll see some errors:

    This happens because TypeScript is trying to figure out the type of React, and what it exports, and is trying to do the same for React DOM.

  • I created the file , and added the following code that creates the module and defines its default export as a React component:

    I first create a TypeScript interface for the properties that the component takes, and then the line declares that the component is the object exported by the module.

  • The object tells Jest to run any TypeScript files through the ts-jest preprocessor, which runs them through the TypeScript compiler and produces JavaScript that Jest can consume.

I’ve recently been getting into TypeScript following a lot of positive blogs about it from Tom Dale and others. Today I’ll show you how I’ve set up a TypeScript project from scratch that uses React, and Webpack for managing the build process. I’ll also discuss my initial impressions of TypeScript and in particular working with TypeScript and ReactJS.

@ReactiveConf: Get started with #TypeScript and #ReactJS: #JavaScript

I’ve recently been getting into TypeScript following a lot of positive blogs about it from Tom Dale and others. Today I’ll show you how I’ve set up a TypeScript project from scratch that uses React, and Webpack for managing the build process. I’ll also discuss my initial impressions of TypeScript and in particular working with TypeScript and ReactJS.

I won’t be going into detail on the specifics of TypeScript’s syntax, but you can read either the TypeScript handbook or the free book TypeScript Deep Dive which will also give you a great introduction to the language.

to create a new project:

, which you can find in my dotfiles. This is slightly risky, as I could accidentally run any executable that’s in that directory, but I’m willing to take that risk because I know what’s installed locally and it saves a lot of typing!

which is where all the config for TypeScript’s compiler lives. There’s a few changes I’ve made to the default config, and the one I’m using is below:

This rule allows you to use ES2015 style default imports even when the code you’re importing doesn’t have an ES2015 default export.

: true

Often when you want to add TypeScript to an existing project TypeScript makes it easy by not throwing an error when you don’t declare the types of variables. However, when I’m creating a new TypeScript project from scratch I’d like the compiler to be as strict as possible.

You can read more about this in the TypeScript Deep Dive.

This is another option that makes TypeScript’s compiler stricter. The TypeScript Deep Dive book has a great section on this option. With this option on, TypeScript will spot more occasions where you’re referencing a value that might be undefined, it will error at you. For example:

, it will error and make sure you deal with it. This prevents runtime errors so it seems like a pretty good option to enable from the get go.

Setting up Webpack, Babel and TypeScript

I’m a big Webpack fan; I enjoy the ecosystem of plugins available, I like the developer workflow and it’s good at managing complex applications and their build pipeline. Therefore, even though we could just use TypeScript’s compiler, I’d still like to add Webpack in. We’ll also need Babel because the TypeScript compiler is going to output ES2015 + React for us, so we’ll get Babel to do the work. Let’s install Webpack, Babel and the relevant presets, along with ts-loader, the Webpack plugin for TypeScript.

, and how it compares.

At this point I have to thank Tom Duncalf, whose blog post on TypeScript 1.9 + React was a brilliant starting point for me and I highly recommend it.

There’s nothing too surprising in the Webpack config, but I’ve left some comments in the code to explain it:

const webpack = require ( ‘webpack’ ) const path = require ( ‘path’ ) module . exports = { // put sourcemaps inline devtool : ‘eval’ , // entry point of our application, within the `src` directory (which we add to resolve.modules below): entry : [ ‘index.tsx’ ], // configure the output directory and publicPath for the devServer output : { filename : ‘app.js’ , publicPath : ‘dist’ , path : path . resolve ( ‘dist’ ) }, // configure the dev server to run devServer : { port : 3000 , historyApiFallback : true , inline : true , }, // tell Webpack to load TypeScript files resolve : { // Look for modules in .ts(x) files first, then .js extensions : [ ‘.ts’ , ‘.tsx’ , ‘.js’ ], // add ‘src’ to the modules, so that when you import files you can do so with ‘src’ as the relative route modules : [ ‘src’ , ‘node_modules’ ], }, module : { loaders : [ // .ts(x) files should first pass through the Typescript loader, and then through babel { test : / \. tsx ? $/ , loaders : [ ‘babel-loader’ , ‘ts-loader’ ], include : path . resolve ( ‘src’ ) } ] }, }

that contains the presets that we need:

And with that, we’re now ready to write our TypeScript application.

, which will be our application’s entry point. For now we can create a dummy component and render it to check it’s all working.

If you run Webpack now against this code you’ll see some errors:

This happens because TypeScript is trying to figure out the type of React, and what it exports, and is trying to do the same for React DOM. React isn’t authored in TypeScript so it doesn’t contain that information, but thankfully for this situation the community has created DefinitelyTyped, a large repository of types for modules.

scope, so to get the types for React and ReactDOM we run:

package too, or if you want to see if it has types available, you can use the TypeSearch website to do so.

, that will do just that:

file and use it to build our application.

output that confirms it’s all working.

file that loads our compiled code:

on port 3000, and we have TypeScript working!

either. In this case, we have to add the types to our application so TypeScript knows how to type it. Whilst this can seem annoying, the benefits of having TypeScript at least know a little about all your third party dependencies will save you debugging time.

(the ‘d’ is for ‘declaration’) and you can read more about them on the TypeScript docs. TypeScript will automatically find these files in your project, you don’t need to explicitly import them.

, and added the following code that creates the module and defines its default export as a React component:

declares that the component is the object exported by the module. By typing the properties, TypeScript will tell me if I typo a property or forget to pass one, which is really valuable.

package so you can have all your tests type-checked too.

, with some settings:

files, which is my preferred naming convention for tests.

and have everything work as expected.

Although TypeScript gives you a lot of checks on your code, I still wanted a linter to enforce some code style and quality checks. Much like ESLint to JavaScript, TSLint is the best option for checking TypeScript files. It works in the same way as ESLint – with a set of rules that you enable or disable, and there’s also a TSLint-React package to add React specific rules.

presets, which enables a bunch of rules. I disagree with some of the defaults though so I override them – you might choose to do differently – this is up to you!

to lint my project.

In summary, I’ve found TypeScript to be a joy to work with so far. I’ll definitely be blogging more about the specifics of the language and how I’m using it, but in terms of setting up a build process, configuring all the tools and getting started with types, it’s been a real joy. I’d highly recommend giving it a go if you’re looking for a bit more structure in your JS applications and want a strong compiler to help you avoid mistakes and spend less time debugging.

If you’d like to browse the code or get started from what I created in this post, I pushed an example repo to GitHub that you can use as a starting point. Feel free to raise an issue on that repo if you have any questions about it.

Getting started with TypeScript and React