Learn how to set up a React project using TypeScript with Create React App, custom Webpack configurations, and Next.js.
In this section, we will explore how to set up a React project using TypeScript. React is a powerful JavaScript library for building user interfaces, and TypeScript enhances it by providing static typing. This combination allows developers to write more robust and maintainable code. We will cover several methods to get your React TypeScript project up and running, including using Create React App, setting up a custom Webpack configuration, and leveraging Next.js.
Before diving into the setup process, let’s briefly discuss why TypeScript is beneficial when working with React:
Create React App (CRA) is a popular tool for bootstrapping React applications. It abstracts away the complex configuration and allows you to focus on writing code. Let’s see how to set up a React project with TypeScript using CRA.
Before we begin, make sure you have Node.js and npm (Node Package Manager) installed on your machine. You can download them from Node.js official website.
To verify the installation, open your terminal and run:
node -v
npm -v
Run the following command to create a new React project with TypeScript:
npx create-react-app my-react-app --template typescript
npx
is a package runner tool that comes with npm 5.2+.create-react-app
is the command to create a new React application.my-react-app
is the name of your project. Feel free to change it to whatever you prefer.--template typescript
specifies that we want to use the TypeScript template.Once the setup is complete, navigate into your project directory:
cd my-react-app
To start the development server and see your application in action, run:
npm start
This command will open your default web browser and display the React application running at http://localhost:3000
.
Here’s a brief overview of the project structure:
my-react-app/
├── node_modules/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── App.tsx
│ ├── index.tsx
│ ├── react-app-env.d.ts
│ ├── reportWebVitals.ts
│ └── setupTests.ts
├── package.json
├── tsconfig.json
└── README.md
src/
: Contains the TypeScript source files for your React application.tsconfig.json
: TypeScript configuration file.package.json
: Lists the project dependencies and scripts.Open src/App.tsx
in your code editor and modify the component to see TypeScript in action:
import React from 'react';
interface AppProps {
message: string;
}
const App: React.FC<AppProps> = ({ message }) => {
return (
<div className="App">
<h1>{message}</h1>
</div>
);
};
export default App;
In this example, we define a simple App
component that takes a message
prop of type string
.
For more control over your project setup, you might want to configure Webpack manually. This approach is more advanced but allows for greater customization.
Create a new directory for your project and initialize it with npm:
mkdir my-react-app
cd my-react-app
npm init -y
Install React, React DOM, TypeScript, and Webpack-related packages:
npm install react react-dom
npm install --save-dev typescript ts-loader webpack webpack-cli webpack-dev-server @types/react @types/react-dom
ts-loader
is a TypeScript loader for Webpack.@types/react
and @types/react-dom
provide TypeScript types for React.Create the following files and directories:
src/
: Create a directory for your source files.src/index.tsx
: Entry point for your application.public/index.html
: HTML template for your application.webpack.config.js
: Webpack configuration file.tsconfig.json
: TypeScript configuration file.Create a webpack.config.js
file with the following content:
const path = require('path');
module.exports = {
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
devServer: {
contentBase: path.join(__dirname, 'public'),
compress: true,
port: 9000,
},
};
Create a tsconfig.json
file with the following content:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"jsx": "react",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
Create a src/index.tsx
file with a simple React component:
import React from 'react';
import ReactDOM from 'react-dom';
const App: React.FC = () => {
return <h1>Hello, TypeScript with React!</h1>;
};
ReactDOM.render(<App />, document.getElementById('root'));
Create a public/index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React TypeScript App</title>
</head>
<body>
<div id="root"></div>
<script src="../dist/bundle.js"></script>
</body>
</html>
Add the following scripts to your package.json
:
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production"
}
To start the development server, run:
npm start
Next.js is a React framework that provides server-side rendering and other powerful features. It has built-in support for TypeScript.
Run the following command to create a new Next.js project with TypeScript:
npx create-next-app my-next-app --typescript
Once the setup is complete, navigate into your project directory:
cd my-next-app
To start the development server, run:
npm run dev
This command will open your default web browser and display the Next.js application running at http://localhost:3000
.
Open pages/index.tsx
in your code editor and modify the page to see TypeScript in action:
import React from 'react';
const Home: React.FC = () => {
return (
<div>
<h1>Welcome to Next.js with TypeScript!</h1>
</div>
);
};
export default Home;
Now that you’ve learned how to set up a React TypeScript project using different methods, try experimenting with the code examples. Modify the components, add new features, or integrate external libraries to see how TypeScript helps you catch errors early and improve your development workflow.
Setting up a React project with TypeScript can significantly enhance your development experience by providing type safety and better tooling. Whether you choose Create React App, a custom Webpack configuration, or Next.js, each method offers unique advantages. As you become more comfortable with TypeScript and React, you’ll be able to build more complex and scalable applications with confidence.