Setting React - Laravel Without using Laravel mix

Setting React - Laravel Without using Laravel mix

When it comes to web development, my goto library on the front end is React, and on the backend, I love to use Laravel because of the many built-in goodies it contains.

More than once i have found my self having to host my backend and my frontend separately, and running multiple deployments. Although it has its benefit, it can be quite expensive to maintain. Deploying your react and laravel app on the same server still gives you most of the benefits of deploying them separately. They might live on the same server but they are still two reusable entities communicating with each other. Let me show how you can set up your laravel and react project on one server.

For this task, we are going to be making use of Babelwebpack and react-hot-loader to compile our react assets into the laravel view.

Laravel

First, we are going to create our laravel project. We can do that by running the command.

laravel new react-laravel

You can learn more about creating a laravel project here.

In our /resources/view/ folder, we can find a file named welcome.blade.php. Delete the file and create a new file called index.blade.php with the following content.

<!-- sourced from https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html -->
<!DOCTYPE html>
<html>

<head>  <meta charset="UTF-8" />  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">  <title>Reavel</title> </head>

<body>  <div id="root"></div>  <noscript>   You need to enable JavaScript to run this app.  </noscript>  @if(env('APP_ENV') === 'local')   <script src="http://localhost:3000/js/app.js"></script>  @else  <script src="/js/app.js"></script>  @endif </body>

</html>

Line 16 checks if we are running in development mode so that it can fetch the compiled asset from the webpack dev server. It's important that you update your APP_ENV in the env file to 'production' when in a production environment.

Then we have to modify our route to point to that file. So will head into our routes folder and open web.php. We will replace 'welcome' with 'index' and our file should end up looking like this:

<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
  return view('index');
});

package.json

Now it's time to modify our package.json file which can be found in the root of the project. A number of modules will not be needed, so we should modify the file to look like this.

{
  "private": true,
  "scripts": {
    "start": "webpack-dev-server --mode development",
    "build": "webpack"
  }
}

We will install all we need along the line.

React

Now we want to add react to our laravel project. Create a folder named 'src' in the root of our laravel project. Next, let's get Babel

Babel

To install babel, let's run 

npm install --save-dev @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected]

We won't go into details of what each of this packages do so that this article doesn't get too long, but I will advise that you do your little research if you are not yet familiar with them.

Create a file named .babelrc in the project root. We will be setting the presets for babel by inputting this content in the file.

{
 "presets": ["@babel/env", "@babel/preset-react"]
}

Webpack

Now we need to get and configure webpack. To do that we will need to install a few more packages. Let's run 

npm install --save-dev [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

Webpack uses loaders to process different types of files. it also comes with a development server that will use to bundle and serve our React project during development. You can do some research on webpack if you are not already familiar with it.

Create a new file named webpack.config.js also at the root of the laravel project. This file exports an object which will be our webpack configuration.

const path = require("path");
const webpack = require("webpack");

module.exports = {  entry: "./src/index.js",  mode: "development",  module: {   rules: [    {     test: /.(js|jsx)$/,     exclude: /(node_modules|bower_components)/,     loader: "babel-loader",     options: { presets: ["@babel/env"] }    },    {     test: /.css$/,     use: ["style-loader", "css-loader"]    },    {     test: /.scss$/,     use: ['style-loader', 'css-loader', 'sass-loader']    }   ]  },  resolve: { extensions: ["*", ".js", ".jsx"] },  output: {   path: path.resolve(dirname, "public/js"),     publicPath: "http://localhost:3000/js/",   filename: "app.js"  },  devServer: {   contentBase: path.join(dirname, "public/"),   headers: { 'Access-Control-Allow-Origin': '*' },   port: 3000,   hotOnly: true  },  plugins: [new webpack.HotModuleReplacementPlugin()] };

This configuration tells webpack what file to start bundling from (entry), the type of files that are transformed(module), files to leave out(exclude), and where it saves the bundled file to (output).

Let's go ahead and install a loader for processing sass files since it’s part of the modules we’ve defined in our config.

npm install sass sass-loader

You can add more loaders depending on your needs.

React

Next, we'll add two more packages by running 

npm install --save [email protected] [email protected]

Notice we are installing these as regular dependencies.

We can now create our index.js file in the src directory. This is the file that tells react when to hook into the dom.

import React from "react";
import ReactDOM from "react-dom";
import App from "./App.js";
ReactDOM.render(<App />, document.getElementById("root"));

We can also create another file in src called App.js. All these should be familiar if you've previously worked with react.

import React from 'react';
import './styles/App.css';

function App() {

 return (   <div className='App'>    <h1>Hello</h1>    <p>What a REAVELation</p>   </div>  ); }

export default App;

From our webpack config, our app can also process css, so will create and add a css file. Create a folder named style in our src directory and in the style directory create a filed named App.css. We will add some style to this file

.App {
 margin: 1rem;
 font-family: Arial, Helvetica, sans-serif;
}

Your final project struture should be similar to this:

.
+-- app
+-- bootstrap
+-- config
+-- database
+-- node_modules
+-- public
| +-- .htacess
| +-- favicon.ico
| +-- index.html
| +-- index.php
+-- resources
| +-- views
| | +-- index.blade.php
+-- routes
+-- src
| +-- style
| | +-- App.css
| +-- App.js
| +-- index.js
+-- storage
+-- test
+-- vendor
+-- .env
+-- .env.example
+-- .babelrc
+-- .gitignore
+-- artisan
+-- composer.json
+-- composer.lock
+-- package-lock.json
+-- package.json
+-- server.php
+-- webpack.config.js

We now have a function React & Laravel app! We can start up our dev server to compile our assets by running 

npm start

and the start our php server to run the laravel app by running 

php artisan serve

in the terminal. We should see our app on http://localhost:8000

HMR

If you run the server now, you will notice none of our changes on react updates the app. That is because HMR doesn't know what to replace yet.

We are going to complete our setup by installing react-hot-loader. So run npm install --save react-hot-loader

Now import react-hot-loader in our app and wrap it around the exported component. Your App.js should now look like this

import React from 'react';
import {hot} from 'react-hot-loader';
import './styles/App.css';

function App() {

 return (   <div>    <h1>Hello</h1>    <p>What a REAVELation</p>   </div>  ); }

export default hot(module)(App);

Now our app will be updated as we make changes to the react app. Changing our PHP files will not cause the app to update, just the js files in the src folder.

When your app is ready for deployment, run npm run build

to build our asset and update the APP_ENV in our env file to 'production' so that laravel will fetch the built asset and not the compiled asset in the dev server.

Conclusion

You can go ahead an tweak the setup according to your need. If anything is still unclear or you want another reference, here is a repo with the implementation on Github.

Thanks for reading.

laravel reactjs react-native webpack web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms? React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. **[Hire...

Hire Dedicated React Native Developer in India | React Native Development

Hire dedicated React Native developers for your next project. As the top react native development company we offer you the best service as per your business needs.

Which is the best React Native app development company in New York?

Hire top react native app development company in New York to build and develop custom react native mobile apps for Android & iOS with the latest features.

Top React Native Mobile App Development Companies in USA

Looking for top React Native mobile app development company in USA for Startups & Enterprise? Find out the top list of React Native mobile app development company in USA.