How to create a React TypeScript application from scratch

Create a new project directory and navigate there:

Init this directory as an npm-package. It will allow you to install third-party packages such as React and TypeScript later:

Install React, React-DOM and TypeScript:

Install type definitions for React and React-DOM. They will allow TypeScript compiler to work with packages and figure out the types that can and cannot be used with

If you use some other packages you will need to install types for those packages too. The DefinitelyTyped repository contains the biggest amount of type declarations for npm packages. You can find the types for your package there and install them.

TypeScript Config#

Generate a tsconfig.json file using npx package runner:

This file is used as settings for TypeScript compiler and tells it how to interpret the code.

After it's done, open this file and add the following option:

This will allow a compiler to work with JSX components as React components.

Setting up Webpack#

Webpack is a static module bundler for modern JavaScript applications. It takes care of compiling, bundling and minifying the code for you.

Install webpack, its command line interface, and html-webpack-plugin:

The latter is used to deal with the html-entrypoint so that we will be able to run our application in a browser.

The ts-loader package is a loader for webpack that knows how to work with TypeScript files. Webpack itself doesn't know that.

Then, create a webpack.config.js file.

Source code#

Create an entry point file src/index.tsx:

Create a first component src/components/App/index.tsx:

Add a template src/index.html file:

Development Server#

Install the webpack-dev-server package:

This package is used to run application while developing. Also, it will reload the application when source code is changed.

Set up development server in your webpack.config.js:

Runner Scripts#

In your package.json file, update scripts section with these scripts:

The build script will build your application in a production mode which creates an optimized production build.

And the dev script will set up a development server on localhost for you to develop the application.

If you now run npm run dev and open http://localhost:9000/ you will see a running app.