Skip to content

Instantly share code, notes, and snippets.

@kresnasatya
Last active May 30, 2024 05:20
Show Gist options
  • Save kresnasatya/2a739b59350bf6f713fabfb6f25813a9 to your computer and use it in GitHub Desktop.
Save kresnasatya/2a739b59350bf6f713fabfb6f25813a9 to your computer and use it in GitHub Desktop.
Experiment of integrating Laravel and Svelte with Inertia

Experiment integrate Laravel + Svelte with Inertia. Case study is Chirper from Laravel Bootcamp.

Specification

  • Laravel version 11.x
  • Svelte version 4.x
  • Inertia version 1.x

Setup

  • Install Laravel

    • Run php artisan serve
  • Install Laravel Breeze + Breeze with Blade option

    • composer require laravel/breeze --dev
    • php artisan breeze:install blade
  • Install Inertia Laravel

    • composer require inertiajs/inertia-laravel
    • Setup @inertiaHead and @inertia in layouts/app.blade.php
    • Setup Inertia middleware with php artisan inertia:middleware
    • IMPORTANT! Change $rootView from 'app' to 'layouts/app' in HandleInertiaRequests middleware. Why? Because we follow Laravel Breeze structure. In Laravel Breeze, app.blade.php stored in layouts folder.
  • Install Inertia Svelte

    • npm install @inertiajs/svelte
    • npm install --save-dev @sveltejs/vite-plugin-svelte for Svelte integrate with Vite
    • Update vite.config.js
      import { defineConfig } from 'vite';
      import laravel from 'laravel-vite-plugin';
      ++ import { svelte } from '@sveltejs/vite-plugin-svelte';
      ++ import { resolve } from 'path';
      
      export default defineConfig({
          plugins: [
              laravel({
                  input: [
                      'resources/css/app.css',
                      'resources/js/app.js',
                  ],
                  refresh: true,
      ++        }),
      ++        svelte({})
          ],
      ++    resolve: {
      ++        alias: {
      ++            '@': resolve(__dirname, 'resources/js')
      ++        },
      ++        extensions: ['.js', '.svelte', '.json']
      ++    }
      });
    • The add @ symbol in vite.config.js is an alias for resolve paths. It useful when you import file

    Good:

    import Layout from '@/Layouts.svelte';

    Bad:

    // If you import Layout from Dashboard.svelte it will be like this
    import Layout from '../Layouts/Authenticated.svelte';
    
    // If you import Layout from Chirps/Index.svelte it will be like this
    import Layout from '../../Layouts/Authenticated.svelte';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment