How to install & use ReactJS in TypeScript with Laravel 8 & Laravel Mix 6

Bijaya Prasad Kuikel
2 min readFeb 13, 2021

--

Laravel is one of the most loved web frameworks available. It makes development so easier and fun. React is one of the most loved JavaScript Library because of it’s simplicity. In this article we will learn to implement Reactjs in TypeScript with Laravel Mix (Laravel Mix is a tool for compiling and optimizing assets in a Laravel app).

Why TypeScript?

Many developers love TypeScript. The reason is it simplifies JavaScript code, as it adds the readability and writability and makes easier to debug. It gives us all the benefits of the modern JavaScript (ES6 & beyond) also can help us to avoid painful bugs that developers commonly run into when writing JavaScript by type checking the code.

Let’s get started:

We can start by scaffolding a new laravel app using the command:
laravel new larareacts

Install typescript globally on your local machine:

yarn global add typescript or npm install -g typescript

Now let’s install React & react -dom with their types:

yarn add react react-dom @types/react @types/react-dom

Also we need to install ts-loader and typescript as dev dependencies:

yarn add ts-loader typescript @babel/preset-react--dev

Now we need to generate tsconfig.json file using the following command:

tsc --init --jsx react

Now let’s update our webpack.mix.js file:

const mix = require("laravel-mix");mix.ts("resources/js/app.tsx", "public/js").react();

Now let’s create a index file inside: resources/js named index.tsx :

import React from "react";import { render } from "react-dom";import App from "./components/App";render(<App />, document.getElementById("app"));

We need to create a root App component inside resources/js/components folder with the following contents:

Also within our welcome.blade.php update the content to have something like this:

<body>
<div id="app"></div>
<script src="{{ asset('js/app.js') }}"></script></body>

Install all the dependencies: yarn or npm install

Compile the assets with the command: yarn dev or npm run dev

Run Laravel server: php artisan serve and access: http://localhost:8000

YOU CAN WATCH MY VIDEO ON INSTALLING REACT WITH TYPESCRIPT ON SCRATCH:

--

--