Hello Artisan,
In this tutorial, I will show you, how to install react js in Laravel 9 with vite. Vite is a frontend build tool that provides an extremely powerful and fast development environment and bundles your code for production.
So if you don't know how to install react js with vite in Laravel 9 application then this example is for you. After releasing vite in Laravel 9.x, 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.
So let's see the installation process of vite in Laravel 9.x with react js.
Step 1: Install Laravel 9
In this step, we will install a fresh Laravel application. Run the below command to install:
composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-react-vite
Step 2: Install NPM
Run the following command to install frontend dependencies:
npm install
Step 3: Install React
Now after installing node modules we need to install react js in our application by the following command:
npm install react@latest react-dom@latest
Now we have to install vitejs/plugin-react plugin. So install it by the below command:
npm i @vitejs/plugin-react --force
npm i @vitejs/plugin-react-refresh --force
Now we have to update vite.config.js
file like the below:
vite.config.js
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(),
],
});
Now run the below command to compile our assets.
npm run dev
Step 4: Create React Component
Under the resources/js
folder create a file name App.jsx
and update it like:
resources/js/App.jsx
Stpe 5: Update app.js file
Now update app.js file like below:
resources/js/app.js
import './bootstrap';
import './App.jsx'
Step 6: 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. Now update the helper.php file like below:
app\helpers.php
Step 7: Update master.blade.php
Now update the master.blade.php like below:
resources/views/layouts/master.blade.php
Now start the local server by changing the app url:
.env
APP_URL=http://localhost:8000
Read also: How To Install Vue 3 in Laravel 9 with Vite Tutorial
Hope it can help you.
#laravel #laravel-9x #vite-laravel #react-js