Originally published on php-apps.learnio.dev — part of the Using Native PHP course. View this lesson on the original site.

Exploring Hot Reloading in PHP Applications

Hot reloading is a powerful feature that allows developers to see changes in their applications instantly without needing to refresh the entire page. This is particularly useful in a development environment where rapid iteration is key. In this lesson, we will explore how to set up hot reloading using Vite HMR (Hot Module Replacement) alongside the native:watch command.

Setting Up Vite for Hot Reloading

To begin, ensure that you have Vite installed in your project. If you haven't done so already, you can install it using npm:

npm install --save-dev vite

Next, you will need to configure Vite for your PHP application. Create a vite.config.js file in the root of your project with the following content:

import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    port: 3000,
    hmr: true, // Enable Hot Module Replacement
  },
});

This configuration sets up Vite to run on port 3000 and enables HMR, allowing for live updates.

Using the native:watch Command

The native:watch command is a part of the Laravel framework that watches for changes in your application files and automatically refreshes the browser. To use this command, ensure your development server is running:

php artisan serve

Then, in another terminal window, run the native:watch command:

php artisan native:watch

This command will monitor your files for changes and trigger a refresh in the browser whenever a change is detected.

See it with a Command Diagram

flowchart TD
    A[Start Development Server] --> B{Run Vite}
    B -->|HMR Enabled| C[Enable Hot Reload]
    C --> D[Make Changes in Code]
    D --> E[Automatic Browser Refresh]

Try it with Runnable Commands

  1. Install Vite:

    npm install --save-dev vite
    
  2. Create or update your vite.config.js:

    import { defineConfig } from 'vite';
    export default defineConfig({
      server: { port: 3000, hmr: true },
    });
    
  3. Start your development server:

    php artisan serve
    
  4. Run the native:watch command:

    php artisan native:watch
    

If it Goes Wrong

If you encounter issues with hot reloading, check the following:

  • Ensure that Vite is correctly installed and configured.
  • Verify that your development server is running and accessible.
  • Check your browser console for any errors related to HMR.

Remember

Hot reloading significantly speeds up the development process by allowing you to see changes in real-time. Make sure to leverage both Vite and the native:watch command for an efficient workflow.

From Using Native PHP — Environment setup and development workflow