TypeScript Create React App

Kenny DuMez
Kenny DuMez
Graphite software engineer

In this guide, we'll walk through setting up a new React project with TypeScript using Create React App.

Create React App is an officially supported command-line interface (CLI) tool from Facebook that helps developers to create single-page React applications quickly without dealing with complex configurations. It sets up the environment so you can use the latest JavaScript features, providing a good developer experience and optimizing the application for production.

Before you start, ensure you have the following installed:

  • Node.js (LTS version recommended)
  • npm (comes with Node.js) or yarn (alternative package manager)

To create a new React app with TypeScript, you can use the npx command, which comes with npm 5.2+ and higher. npx allows you to run command-line tools from npm without installing them globally.

Open your terminal and run the following command:

Terminal
npx create-react-app my-app --template typescript

Here, my-app is the name of your project. You can replace it with your preferred project name. The --template typescript flag tells Create React App to use the TypeScript template.

This command does a few things: - npx: Executes the Create React App CLI without requiring a global installation. - create-react-app: The CLI command to scaffold new React applications. - my-app: The directory name for your new application. - --template typescript: Specifies that you want to use the TypeScript template.

Once the setup is complete, navigate to your project directory:

Terminal
cd my-app

To start the development server, run:

Terminal
npm start

This command starts the development server and opens your new React app in the browser. You should see the default CRA welcome screen.

Your newly created React app with TypeScript will have the following structure:

Terminal
my-app/
├── node_modules/
├── public/
│ ├── index.html
│ └── ...
├── src/
│ ├── App.css
│ ├── App.test.tsx
│ ├── App.tsx
│ ├── index.css
│ ├── index.tsx
│ ├── logo.svg
│ ├── react-app-env.d.ts
│ ├── reportWebVitals.ts
│ └── setupTests.ts
├── package.json
├── tsconfig.json
└── ...
  • src/: This directory contains the source code for your React app.
    • App.tsx: The main component of your app.
    • index.tsx: The entry point of your app.
    • react-app-env.d.ts: Provides TypeScript with information about the environment.
    • tsconfig.json: The TypeScript configuration file.
  • public/: This directory contains static files like index.html.
  • package.json: Lists the project dependencies and scripts.

By default, CRA with TypeScript comes with a few type definitions. You can add more types as needed.

Typescript also leverages props to provide structure to components. Props (short for properties) are used to pass data and event handlers from a parent component to a child component in frameworks like React. They help maintain a structured and manageable way of controlling component behavior and rendering dynamic content based on the passed data.

For example, let's create a new component with typed props:

Terminal
// src/components/Greeting.tsx
import React from 'react'
interface GreetingProps {
name: string
}
const Greeting: React.FC<GreetingProps> = ({ name }) => {
return <h1>Hello, {name}!</h1>
}
export default Greeting

In this example, we define an interface GreetingProps that describes the props our Greeting component expects. The name prop must be a string. This ensures type safety and provides better developer experience with autocompletion and type checking.

To use the Greeting component, import it and include it in your App.tsx:

Terminal
// src/App.tsx
import React from 'react'
import Greeting from './components/Greeting'
const App: React.FC = () => {
return (
<div className="App">
<Greeting name="World" />
</div>
)
}
export default App

Exporting a component makes it available to be used in other parts of an application by including an export keyword before the component definition. This allows other files or components to import and utilize the exported component, facilitating modular and reusable code architecture.

The tsconfig.json file is where you configure TypeScript options. CRA provides a sensible default configuration, but you can customize it according to your needs. Here is an example tsconfig.json:

Terminal
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}

This example configuration specifies that the code should compile to ES5 (a version of JavaScript), making it compatible with older browsers. The configuration also enables various features, such as allowing JavaScript files (allowJs), importing JSON modules (resolveJsonModule), and using JSX syntax (jsx) set specifically for React, ensuring interoperability with CommonJS and ES modules. Additionally, it enforces stricter coding practices (strict), like consistent file naming (forceConsistentCasingInFileNames) and preventing fall-through cases in switch statements (noFallthroughCasesInSwitch), while excluding output generation (noEmit), focusing solely on type-checking and syntax verification.

You can add additional packages to your project using npm or yarn. For example, to add React Router for navigation, run:

Terminal
npm install react-router-dom @types/react-router-dom

The @types/react-router-dom package provides TypeScript definitions for React Router.

To maintain code quality, you can integrate ESLint and Prettier into your project. CRA with TypeScript already includes ESLint, but you can customize it further.

Install Prettier and ESLint configuration for Prettier by running:

Terminal
npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier

Create a .prettierrc file for Prettier configuration:

Terminal
{
"singleQuote": true,
"semi": false
}

This file specifies the formatting rules to automatically apply to your codebase for consistency and style adherence.

Update your .eslintrc.json to include Prettier:

Terminal
{
"extends": ["react-app", "plugin:prettier/recommended"],
"rules": {
"prettier/prettier": "error"
}
}

Updating your .eslintrc.json to include Prettier ensures that your code not only adheres to the best practices and conventions defined by ESLint but also aligns with the consistent formatting enforced by Prettier. This integration allows for the automatic highlighting of style issues as errors, which can be fixed on-the-fly, improving code quality and efficiency.

  • To start the development server, use:
    Terminal
    npm start
  • This command compiles the TypeScript code and opens your application in a web browser, watching for any changes you make to the files.
  • To build the application for production, use:
    Terminal
    npm run build
  • This command prepares the application for deployment, optimizing and minifying the code.

You have now created your first react app using Create React App and TypeScript!

For further reading see the official Create React App documentation.

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2