This article explains what TypeScript is and how to use it in React projects. Finally, we’ll do a small Demo with TypeScript and current React like hooks (useState, useEffect, useReducer, useContext)

This article is not an introduction to TypeScript. Therefore, the basic TypeScript and JavaScript syntax won’t be covered much. However, you don’t have to know typescript and javascript, because the following will try to follow the KISS principle (Keep it Simple, stupid).

What is a Typescript

According to official documentation, TypeScript is a typed superset of JavaScript that compiles to pure JavaScript. It is developed and maintained by Microsoft and the open source community. “Superset” means that Typescript includes all the features and capabilities of JavaScript. TypeScript is a typed scripting language.

It gives developers more control over their code base through its type annotations, classes, and interfaces, so they don’t have to manually fix annoying bugs in the console.

Why use Typescript

  1. Fewer bugs

TypeScript checks for types at compile time and throws errors when variable types change. Being able to catch these obvious but frequently occurring errors early makes it easier to manage your code types.

  1. Refactoring is easier

Explicitly defined data structure and type annotations make code more readable. Code editor support for TS allows you to write programs quickly.

When to use Typescript

It is recommended for use in two situations

  • If you build one that canLong-term maintenanceApplication. Because it can cultivate self-documented code, it can help other developers easily understand your code when they add it to your code base.
  • You need to create alibrary. Because it will help the code editor suggest appropriate types to developers using the library.

Set TypeScript in the React project

Create React App + TypeScript

To start a new Create React App project, you can run this…

npx create-react-app my-app
Copy the code

To add TypeScript to the Create React App project, first install it and its respective @types:

cd my-app
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Copy the code

Next, rename the file (for example, rename index.js to index.tsx), and then restart the local development server!

Method 2: Use Webpack to set up TypeScript

Webpack is a static module wrapper for JavaScript applications.

Let’s start by creating a new directory for our project:

mkdir react-webpack
cd react-webpack
Copy the code

We will use NPM to initialize our project:

npm init -y
Copy the code

The command above will generate a package.json file with some default values. We also need to add dependencies for WebPack, TypeScript, and some React specific modules.

#Installing devDependencies

npm install --save-dev @types/react @types/react-dom awesome-typescript-loader css-loader html-webpack-plugin mini-css-extract-plugin source-map-loader typescript webpack webpack-cli webpack-dev-server

#installing Dependencies
npm install react react-dom
Copy the code

We also need to manually add a few different files and folders under the React-webpack folder:

  1. addwebpack.config.jsTo add webPack-related configuration.
  2. Add to all of our TypeScript configurationstsconfig.json.
  3. Add a new directorysrc.
  4. insrcCreate a new directory in the foldercomponents.
  5. Finally, in thecomponentsAdd to folderIndex.html, app. TSX and index.tsx.

The project structure

├ ─ ─ package. Json ├ ─ ─ package - lock. Json ├ ─ ─ tsconfig. Json ├ ─ ─ webpack. Config. Js ├ ─ ─ the gitignore └ ─ ─ the SRC └ ─ ─ components ├ ─ ─ App.tsx ├─ index. TSX ├─ index.htmlCopy the code

To start adding some code we’ll start with index.html:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title> react-webpack Setup</title> </head> <body> <div id="root"></div> </body> </ HTML >Copy the code

This will create HTML with an empty div with the ID root.

Let’s add code to our React component app.tsx:

import * as React from "react";
export interface HelloWorldProps {
  userName: string;
  lang: string;
}
export const App = (props: HelloWorldProps) = > (
  <h1>
    Hi {props.userName} from React! Welcome to {props.lang}!
  </h1>
);
Copy the code

We create an interface object, HelloWorldProps, with userName and lang as strings.

We pass props to our App component and export it. Now, let’s update the code in index.tsx:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { App } from "./App";
ReactDOM.render(
  <App userName="Beveloper" lang="TypeScript" />.document.getElementById("root"));Copy the code

We just imported the App component into index.tsx. When WebPack sees any file with a.ts or.tsx extension, it uses the awesome-typescript-loader library to translate the file.

We’ll then add some configuration to tsconfig.json:

{
  "compilerOptions": {
    "jsx": "react"."module": "commonjs"."noImplicitAny": true."outDir": "./build/"."preserveConstEnums": true."removeComments": true."sourceMap": true."target": "es5"
  },
  "include": [
    "src/components/index.tsx"]}Copy the code

Let’s also look at the different options we added to tsconfig.json:

  • compilerOptionsRepresents different compiler options.
  • jsx:reactAdd support for JSX in.tsx files.
  • moduleGenerate module code.
  • noImplicitAnyRaises an error for an implied declaration of type any.
  • outDirRepresents the output directory.
  • sourceMapGenerate a.map file, which is useful for debugging applications.
  • targetRepresents the target ECMAScript version to convert our code to (we can add a version based on our specific browser requirements).
  • includeUse to specify a list of files to include.

Webpack Configuration Let’s add some Webpack configuration to webpack.config.js.

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
  entry: "./src/components/index.tsx".target: "web".mode: "development".output: {
    path: path.resolve(\__dirname, "build"),
    filename: "bundle.js",},resolve: {
    extensions: [".js".".jsx".".json".".ts".".tsx"],},module: {
    rules: [{test: /\.(ts|tsx)$/,
        loader: "awesome-typescript-loader"}, {enforce: "pre".test: /\.js$/,
        loader: "source-map-loader"}, {test: /\.css$/,
        loader: "css-loader",}]},plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(\__dirname, "src"."components"."index.html"),}),new MiniCssExtractPlugin({
      filename: "./src/yourfile.css",})]};Copy the code

Let’s look at the different options we added to webpack.config.js:

  • Entry This specifies the entry point for our application. It could be a single file or an array of files that we want to include in the build.

  • Output This contains the output configuration. Path represents the output directory of the code to be output, and filename represents the same filename. It is usually named bundle.js.

  • Resolve Webpack uses this property to decide whether to pack or skip files. Therefore, in our project, WebPack will consider packaging files with.js,.jsx,.json,.ts, and.tsx extensions.

  • Module We can use loaders to make WebPack load specific files when the application requests them. It requires a rule object that specifies:

  • Any to.tsx or.ts Files ending with an extension should be usedawesome-typescript-loader To load;
  • In order to.jsFiles ending with extensions should be usedsource-map-loaderLoad;
  • In order to.cssFiles ending with the extension should be usedcss-loaderLoad.
  • pluginsWebpack has its own limitations, and it provides plug-ins to overcome them and extend its capabilities. For example,html-webpack-pluginCreate a template file from./src/component/index.htmlIn the directoryindex.htmlThe file is rendered to the browser.

The MiniCssExtractPlugin renders the application’s parent CSS file.

Add the script to package.json

We can add different scripts to the package.json file to build the React application:

"scripts": {
    "start": "webpack-dev-server --open"."build": "webpack"
},
Copy the code

Now, run NPM start from the command line. If all goes well, you should see:

Running NPM Run Build will build the Webpack for production and will create a build folder for us.

We’ve seen how to set up TypeScript from scratch using the Create React App and WebPack configuration methods. In the next installment, we’ll do a little Demo of TypeScript with current React like hooks (useState, useEffect, useReducer, useContext)

To be continued…