The Old Way — Boilerplate
First, let’s look at a baseline setup for Typescript + React when you aren’t using Meteor. The example I’m going to show uses Webpack to do the Typescript compilation and bundling. Note that it mostly follows the Typescript doc’s example setup.
Here’s our directory structure:
webpack.config.json is almost exactly as shown in the following setup from Typescript’s own documentation.
Here’s what all that moderately complicate configuration does: compiles all files which are loaded by src/index.tsx and bundles them into dist/bundle.js. The .tsx extension is the Typescript equivalent to the .jsx extension from React. It allows you to write JSX inside your Typescript.
Another step of boilerplate we need is to configure Typescript by defining a special config file
This tells the compiler where our files are and how to compile them.
Now to actual run this build step, we need to set up some scripts in package.json:
To build the scripts once, we run
npm run webpackand if we want to run the webpack dev server (which will auto recompile our sources and provide a simple index-traversing http server) we run
npm run webpack-dev-serverLastly, since we’ve decided to not bundle React / ReactRouter (in order to speed up Typescript recompilation time) by specifying the “externals” configuration in the Webpack config file, we need to have an index.html which resembles the following
Now we can finally render a simple Typescript + React component
The New Way — Meteor 1.3 + Typescript
Now let’s convert this to Meteor 1.3.
Our new directory structure is going to look like the following
Also, our package.json file can be greatly simplified
Much simpler already. No webpack, webpack loaders, source map generators, and no build commands.
Let’s start the Meteor magic up. We’re going to create a new Meteor project in this folder
cd project/folder/
meteor create .By default Meteor creates projects which support Blaze, a Handlebars-like reactive templating system. Since we’re not going to use Blaze, let’s drop the packages which support it
meteor remove blaze-html-templates tracker And add the (soon to be official, I think) Typescript compiler package
meteor add barbatus:typescript static-htmlThe additional static-html package replaces the blaze-html-templates package mentioned above. You can read more about that here.
Also, since Meteor handles the loading of our JS and now bundles NPM packages, we can reduce our index.html file to just the following
That’s it. No need to reference bundle files, or external dependencies, or even write the entire <html> and <head> tags!
Meteor does this all for us.
Now to run the app, do the following
$ npm install
$ meteorThis will install react / react-dom from NPM and Meteor (since 1.3) will bundle them up for use on the client just like Webpack! Typescript is also compiled by the Meteor package we installed, and all with zero Typescript configuration!