How To Install React in Laravel 9 with Vite - TechvBlogs

How To Install React in Laravel 9 with Vite

In this short blog, You will learn How to Install React in Laravel 9 with Vite.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

1 year ago

TechvBlogs - Google News

 Laravel has just released “laravel 9.19” with a major change. There is no more webpack.mix.js file in the laravel root in the place of the webpack.mix.js file vite.config.js file is introduced.

In this post, we will learn how to install React js 3 in laravel 9.19 with vite ?. This post shows you how to install React in laravel 9 with the latest upgrades. If you want to see an example of installing react 3 in laravel-vite then you are in the right place. Laravel 9.19 with vite is the latest version of the laravel framework at the writing of this article. As you know Laravel is the most popular PHP framework and it’s easy to use scale, and flexible.

React is an open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.

By the end of this post, you’ll be able to create a React and Laravel 9.19 application powered by vite. We’ll also learn how to create a react component and connect it with laravel 9 blade file.

How To Install React in Laravel 9 with Vite

Use the following steps to install React in the laravel 9 application.

  1. Install laravel 9 App

  2. Install NPM Dependencies

  3. Install React

  4. Install vitejs/plugin-react plugin

  5. Update vite.config.js

  6. Vite Dev Server Start

  7. Create Reactjs Component

  8. Update app.js file in resources folder

  9. Create Custom Helper For Vite Assets

  10. Connect Reactjs Component with Laravel blade file

  11. Update .env file

  12. Start The Local Server

Step 1: Install laravel 9 App

First, open Terminal and run the following command to create a fresh laravel project:

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-react-vite

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel9-react-vite

Step 2: Install NPM Dependencies

Run the following command to install frontend dependencies:

npm install

Step 3: Install React

Now after installing node modules we need to install reactjs in our application, for that execute the following command in the terminal npm install react@latest react-dom@latest. It will install latest version of reactjs and react-dom also. we’ll use it in jsx file.

npm install react@latest react-dom@latest

Step 4: Install vitejs/plugin-react plugin

In laravel 9 latest release install vitejs/plugin-react plugin for installing reactjs in laravel. This plugin provides required dependencies to run the reactjs application on vite. Vite is a  build command that bundles your code with Rollup and it runs on localhost:3000 port to give hot refresh feature.

npm i @vitejs/plugin-react --force
npm i @vitejs/plugin-react-refresh --force

Step 5: Update vite.config.js file

The latest 9.19 Provides a vite.config.js file in the root of the application to configure front-end assets preset import plugin-react and add react() to the plugins array in the defineConfig() function.

import reactRefresh from '@vitejs/plugin-react-refresh';


export default ({ command }) => ({
    base: command === 'serve' ? '' : '/build/',
    publicDir: 'fake_dir_so_nothing_gets_copied',
    build: {
        manifest: true,
        outDir: 'public/build',
        rollupOptions: {
            input: 'resources/js/app.js',
        },
    },
    plugins: [
        reactRefresh(),
    ],
});

Step 6: Vite Dev Server Start

Now after installing the reactjs, we need to start the dev server for vite for that run the following command and it will watch your resources/js/app.js file and resources/css/app.css file. It also starts a vite server on http://localhost:3000. you can not open it in the browser as it is for vite hot reload and it runs in the background and watches the assets of your application like js and CSS.

npm run dev

Step 7: Create Reactjs Component

Under the resources/js folder create a file name App.jsx and write content for this example let’s write simple “Reactjs With Laravel Vite” you can change it according to your requirement.

// resources/js/App.jsx
import React from 'react';
import { createRoot } from 'react-dom/client'

export default function App(){
    return(
        <h1>How To Install React in Laravel 9 with Vite</h1>
    );
}

if(document.getElementById('root')){
    createRoot(document.getElementById('root')).render(<App />)
}

Step 8: Update app.js file in resources folder

In resources/js/app.js Import App.jsx component

// resources/js/app.js
import './bootstrap';

import './App.jsx'

Step 9: Create Custom Helper For Vite Assets

To work around this, we can ping localhost:3000. If it connects, we know the dev server is running and we can render the hot scripts.

This could go in a helpers.php file, learn how to set one up here.

First, let’s extract the code we had written in our Blade template to a helper function. Next, we’ll use Laravel Http facade to ping localhost:3000. If it connects, we know the dev server is running.

<?php

use Illuminate\Support\Facades\Http;
use Illuminate\Support\HtmlString;

function vite_assets(): HtmlString
{
    $devServerIsRunning = false;
    
    if (app()->environment('local')) {
        try {
            Http::get("http://localhost:3000");
            $devServerIsRunning = true;
        } catch (Exception) {
        }
    }
    
    if ($devServerIsRunning) {
        return new HtmlString(<<<HTML
            <script type="module" src="http://localhost:3000/@vite/client"></script>
            <script type="module" src="http://localhost:3000/resources/js/app.js"></script>
        HTML);
    }
    
    $manifest = json_decode(file_get_contents(
        public_path('build/manifest.json')
    ), true);
    
    return new HtmlString(<<<HTML
        <script type="module" src="/build/{$manifest['resources/js/app.js']['file']}"></script>
        <link rel="stylesheet" href="/build/{$manifest['resources/js/app.js']['css'][0]}">
    HTML);
}

Step 10: Connect Reactjs Component with Laravel blade file

Now we need to create a blade file where the reactjs app will load. In the resources/views folder open a file name  welcome.blade.php. Add @vite(‘resources/js/app.js’) at the bottom of the file in the react.blade.php file It will load all the js you need to run the Reactjs code.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>How To Install React in Laravel 9 with Vite</title>

    {{ vite_assets() }}
</head>
<body>
	<div id="root"></div>
</body>
</html>

Step 11: Update .env file

Open .env file and update APP_URL and set APP_URL=http://localhost:8000. It will help vite to check the js and CSS updates and changes them in the browser instantly.

APP_URL=http://localhost:8000

Step 12: Start the Local server

Start the development server

php artisan serve

and navigate to the following link http://localhost:8000/

Thank you for reading this blog.

You can find the GitHub repository here suresh-ramani/laravel-react-vite.

Read Also: Moving A Laravel Webpack Project To Vite

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Comments (8)

ArKa ArKa 7 months ago

The Step 5 was not clear for me. Where should I put reactRefresh() in vite.config.js? And what is that export default ({ command })..... part?

JERRY JOB JERRY JOB 1 year ago

Thanks a lot?

Lifa Matemba Lifa Matemba 1 year ago

Thanks @Suresh Ramani. Your article saved my day. A minor additive to those that had an issue to do with "undefined css" which rose from the helper.php the last line. I fixed it by replacing css with src since my manifest.json had src instead of css. Note that for others you must run npm run build so that a build directory is created in the public folder where you can see the manifest.json file.

Anjanesh Lekshminarayanan Anjanesh Lekshminarayanan 1 year ago

So the reason for vite 3.x not working - it was the port number change in app/helper.php from 3000 to 5173 Vite 3's default port is 5173 instead of 300 when you do npm run dev

https://main.vitejs.dev/config/server-options.html

Anjanesh Lekshminarayanan Anjanesh Lekshminarayanan 1 year ago

Default has changed from 3000 (and not 300 as I missed one 0 in the previous comment) to 5173.

Anjanesh Lekshminarayanan Anjanesh Lekshminarayanan 1 year ago

I'm getting -

file_get_contents(/Users/username/workspace/laravel/laravel9-react-vite/public/build/manifest.json): Failed to open stream: No such file or directory
$manifest = json_decode(file_get_contents(public_path('build/manifest.json')), true);

What am I doing wrong ?

Suresh Ramani Suresh Ramani 1 year ago

You need to change PORT according to Vite Server in app/helper.php

Henrique Henrique 1 year ago

You need to run npm run build once before running npm run dev

Comment


Note: All Input Fields are required.