Creating a React and Typescript app with Webpack
Arpit Malik
Posted on April 23, 2024
In a previous article, I went over how you can setup a simple React app with just Webpack and Babel. But what if you also want to enable Typescript for your project?
This article goes over how to add Typescript support to a simple React + Webpack project.
Step 1: Install Typescript and type definitions
The first step is to just install Typescript:
npm install typescript --save-dev
Then, you'll be required to install the type definitions for all the libraries that you already use. Usually, these would be:
npm install @types/node @types/react @types/react-dom @types/jest --save-dev
Step 2: Configure Webpack
For Webpack to be able to process Typescript files, we will first need to install a custom loader.
There are several available, but we’ll use ts-loader
for our setup:
npm install ts-loader --save-dev
Next, we need to tell Webpack to process TS files as well. For this, we can update the webpack.config.js
file to also support ts
and tsx
extensions:
// webpack.config.js
{
// ...,
module: {
rules: [
// `js` and `jsx` files are parsed using `babel-loader`
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
// `ts` and `tsx` files are parsed using `ts-loader`
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: ["ts-loader"],
}
],
},
resolve: {
extensions: ["*", ".js", ".jsx", ".ts", ".tsx"],
},
}
Step 3: Configure Typescript
The Typescript compiler supports several options for how to treat the code, which are defined in a tsconfig.json
file in the root of the project.
Let’s create one for this project as well:
// tsconfig.json
{
"compilerOptions": {
"jsx": "react",
"noImplicitAny": true,
"module": "ES6",
"target": "ES5",
"outDir": "./build/",
"preserveConstEnums": true,
"removeComments": true,
"sourceMap": true
}
}
For the purpose of this tutorial, I have just added the minimal settings that are required for the React + TS + Webpack integration, but you can learn more about all the options available in the official documentation.
Step 4: Start using Typescript
If you already have some JS files in your project, now is a good time to change their extensions from js to ts and from jsx to tsx!
Then, restart the app and you should see everything still working ✨
Thats it!
Posted on April 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.