How to Run a React TypeScript Project
React is a popular JavaScript library for building user interfaces, and TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Combining React with TypeScript can bring several benefits, such as better code maintainability, early error detection, and improved developer experience. In this blog post, we will explore how to run a React TypeScript project, covering fundamental concepts, usage methods, common practices, and best practices.
Table of Contents#
- Setting up a React TypeScript Project
- Running the Development Server
- Building the Project for Production
- Common Practices and Best Practices
- Conclusion
- References
Setting up a React TypeScript Project#
There are several ways to set up a React TypeScript project. One of the most popular ways is to use Create React App (CRA) with the TypeScript template.
Using Create React App#
Create React App is a tool that helps you set up a new React project with no build configuration. To create a new React TypeScript project using CRA, run the following command in your terminal:
npx create-react-app my-app --template typescript
cd my-appThis command creates a new React project named my-app with the TypeScript template. The cd my-app command changes the current directory to the project directory.
Manual Setup#
If you prefer to set up the project manually, you can follow these steps:
- Create a new directory for your project and navigate to it:
mkdir my-app
cd my-app- Initialize a new npm project:
npm init -y- Install React and ReactDOM:
npm install react react-dom- Install TypeScript and its React types:
npm install --save-dev typescript @types/react @types/react-dom- Create a
tsconfig.jsonfile in the root of your project with the following content:
{
"compilerOptions": {
"target": "ES6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}- Create a
srcdirectory and add your React components and TypeScript files inside it.
Running the Development Server#
Once you have set up your React TypeScript project, you can run the development server to see your application in action.
Using Create React App#
If you used Create React App to set up your project, you can start the development server by running the following command in your project directory:
npm startThis command starts a development server at http://localhost:3000 and opens your application in your default browser. Any changes you make to your code will automatically be reflected in the browser.
Manual Setup#
If you set up your project manually, you need to use a bundler like Webpack or Parcel to serve your application. Here is an example of using Webpack:
- Install Webpack and its related loaders and plugins:
npm install --save-dev webpack webpack-cli webpack-dev-server ts-loader html-webpack-plugin- Create a
webpack.config.jsfile in the root of your project with the following content:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 3000
}
};- Add a
startscript to yourpackage.jsonfile:
{
"scripts": {
"start": "webpack-dev-server --open"
}
}- Run the development server:
npm startBuilding the Project for Production#
When you are ready to deploy your React TypeScript project, you need to build it for production.
Using Create React App#
If you used Create React App to set up your project, you can build it for production by running the following command in your project directory:
npm run buildThis command creates a build directory with optimized and minified versions of your application's files. You can then deploy the contents of the build directory to a web server.
Manual Setup#
If you set up your project manually, you can use Webpack to build your project for production. Add a build script to your package.json file:
{
"scripts": {
"build": "webpack --mode production"
}
}Then run the following command to build your project:
npm run buildCommon Practices and Best Practices#
Component Typing#
When writing React components in TypeScript, it is important to define the types of the component's props and state. Here is an example of a functional component with typed props:
import React from 'react';
interface MyComponentProps {
name: string;
age: number;
}
const MyComponent: React.FC<MyComponentProps> = ({ name, age }) => {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
};
export default MyComponent;Type Assertion#
Type assertion can be used when you know the type of a value better than TypeScript does. However, it should be used sparingly as it can bypass TypeScript's type checking. Here is an example:
const element = document.getElementById('my-element') as HTMLDivElement;Using Enums#
Enums can be used to define a set of named constants. They can be useful in React TypeScript projects for defining things like status codes or action types. Here is an example:
enum Status {
Pending,
Success,
Error
}
const status: Status = Status.Success;Conclusion#
Running a React TypeScript project involves setting up the project, running the development server, and building it for production. Whether you use Create React App or set up the project manually, TypeScript can bring many benefits to your React application. By following common practices and best practices, you can write more maintainable and error-free code.