In modern web development, building a robust, maintainable, reliable, and bug-free application has become super important. Typescript, a superset of JavaScript, has gained popularity for its ability to catch bugs in the early development phase rather than runtime. With explicit types, codes become easy to understand and refactor. In this article, we will learn how we can create a react app with typescript, so you can leverage typescript advantages right away.
Building a new react app with TypeScript
If you are trying to create your new app with typescript, you can check out official docs. You can use a typescript template provided by Facebook, just append --template typescript
to the creation command.
npx create-react-app my-app --template typescript
Note:- When you create a new app, the CLI will use npm or Yarn to install dependencies, depending on which tool you use to run create-react-app
.
Once you run the above command, all the dependencies will downloaded at once required to utilize typescript in your application, all files will use the .ts
extension instead of .js
.
Also read, Easy Tutorial to Create a StopWatch in React
Add Typescript to Existing React App
If you want to convert your existing React app to typescript,
Installation
Go to your project terminal and run the below commands,
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
It will install a typescript compiler and definitelyTyped packages providing type definitions for various libraries (Node.js, React, etc.)
Create tsconfig.json
At the root of your project, add a tsconfig.json
file. This file helps you configure the Typescript compiler. Here is the configuration example you can use with a description to understand,
{
"compilerOptions": {
"target": "es5", // Or "esnext", depending on your target environment
"lib": ["dom", "esnext"], // Libraries to include
"allowJs": true, // Allow compiling .js files (for gradual migration)
"skipLibCheck": true, // Skip type checking of declaration files (can speed up compilation initially)
"esModuleInterop": true, // Enables proper interoperability between CommonJS and ES modules
"strict": true, // Enable all strict type-checking options (recommended for new projects, but consider gradually enabling in existing projects)
"forceConsistentCasingInFileNames": true, // Enforces consistent casing
"module": "esnext", // Or "commonjs" if you are using CommonJS modules
"moduleResolution": "node", // How modules are resolved
"resolveJsonModule": true, // Allows importing JSON files
"isolatedModules": true, // Improves compilation speed
"noEmit": true, // Don't emit output files (handled by Babel or similar)
"jsx": "react" // Use React JSX syntax
},
"include": [
"src/**/*" // Include all files in the src directory
]
}
Integrate with the Build Process
You also need to update the build process to use the TypeScript compiler. Here are the few places you need to update,
Create a React App (CRA) with react-app-rewired
and customize-cra
:
We would use, react-app-rewired
and customize-cra
with Create React App (CRA) when we need to customize the underlying Webpack configuration that CRA provides, but without ejecting from CRA. These help you to add your customizations to the existing configuration.
react-app-rewired
: Acts as a bridge, allowing you to override parts of the CRA configuration.customize-cra
: Provides a set of helper functions to make common customizations easier (like adding TypeScript, Sass, Less, etc.).
npm install --save-dev react-app-rewired customize-cra
Now, Create a config-overrides.js
file in your project root, and below code,
const { override, addTypeScript } = require('customize-cra');
module.exports = override(addTypeScript());
Update your package.json
scripts:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test"
}
Webpack
You will also need to add the ts-loader
or awesome-typescript-loader
to your Webpack configuration.
npm install --save-dev ts-loader
Example how you will configure your WebPack,
// webpack.config.js
module.exports = {
// ... other config
module: {
rules: [
// ... other rules
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'], // Add .ts and .tsx
},
};
Babel
If you are using Babel for transpilation, you’ll need to use the @babel/preset-typescript
preset.
npm install --save-dev @babel/preset-typescript
Here how you will configure your babel file,
// babel.config.js or in package.json
{
"presets": ["@babel/preset-react", "@babel/preset-typescript"]
}
Gradual Conversion
You don’t have to convert the whole project files into TypeScript at once! TypeScript allows gradual adoption. You can convert a few files into typescripts and get comfortable with the type system, then you can slowly expand to the whole project.
Note:- strict: true
Enables a range of strict type checks, which is highly recommended, but you might want to enable these gradually in an existing project to avoid a flood of errors.
Also read, Easy tutorial to build React Autosuggest from scratch
Key Considerations
- Type Error: There’s a learning curve to TypeScript. Don’t be overwhelmed by the initial type errors. Address them systematically and gradually.
- TypeScript Compiler (tsc): The main tool to compile TypeScript to JavaScript.
- IDEs with TypeScript Support: VS Code, WebStorm, and others provide excellent TypeScript support with features like auto-completion, error highlighting, and refactoring.
allowJs
: Use this flag in yourtsconfig.json
during the migration process to allow TypeScript to compile.js
files. This will let you convert one file into a TypeScript one at a time.noEmit
: When using a bundler like Webpack or Babel, setnoEmit: true
intsconfig.json
because the bundler will handle the JavaScript output.
Last Words
Congratulations! Now you have created your react application with typescript. While this guide covered the basics, there’s much more to explore with TypeScript and React. Check out the official documentation for TypeScript and Create React App to dive deeper into advanced topics and best practices.
Also check out our other articles on various topics like JavaScript, React, and Data Structure and Algorithm.