Typescript + React: Getting Started
You might remember our #behind-the-scenes post on adding search to a static site where we showed how we used Typescript & React to make a dynamic search bar and display the results to the user. Let’s rewind that and show how to get started with a Typescript and React to make a simple page.
Let’s first declare our dependencies. We want some dependencies that we only need for development and some dependencies we need for our application to run. The development dependencies are needed to build out our application on our development environment. Our development dependencies are:
- webpack
- webpack-cli
- typescript
- @types/react
- @types/react-dom
- ts-loader
- source-map-loader
We can install all of those by using yarn or npm:
We need webpack, webpack, webpack-cli, and ts-loader to be able to bundle our application into a small executable javascript file. We use the @types to be sure that Typescript understands the definitions of the packages and can detect issues ahead of time. Read more about @types.
The packages we need to actually allow our application to run are:
- react
- react-dom
We can install those using yarn or npm:
Next, let’s specify our Typescript config to specify how our application should be compiled:
We’re telling typescript where to output our built files with the “outDir” and what our target EMCAScript version will be, whch is how JavaScript is standardized. Read more about the typescript config
Let’s make some basic files with React to get it started. We’re going to make an src directory with an App.ts file within it. Then within src we’re going to make a components directory and make a world.tsx file within that.
Now we want to edit our App.ts file to make an entry point to our application. We’ll create our React element, and target an element in HTMl for that to replace and inject our React code.
Now we need to edit our world.tsx file so that something can be rendered:
Let’s create the index.html file that references that .js-world
class:
Next let’ make our webpack file to be able to build the application, called webpack.config.js:
That should be it! Read more about it here Another option is to use create-react-app to use the community supported way of starting a React app with Typescript.