Laravel Vite & Visually Jarring Loading Due to Apparent CSS Injection

388 Views Asked by At

I have a Laravel 10 project & am using Vite (laravel-vite-plugin). I am familiar with WebPack, but am new to Vite and am not sure if I'm doing something wrong or what.

What I want:

  1. develop locally and use HMR (Hot Module Replacement)
  2. when I deploy, run npm run build, have bundled, static assets that I can serve

My issue(s):

  1. Vite seems to be injecting CSS after the request & it looks visually jarring / extremely bad
  2. Specifically, things like images start large & then scale down, backgrounds fill in during dom load, etc (granted, it happens in less than a second, but it just feels very 'off')
  3. I've tried adding a loading spinner to 'cover up' the behavior (which, honestly, I don't even want to use as a method) ...but the spinner is subject to the same 'injection' behavior; i.e. the spinner gets applied as the CSS gets injected & thus, can't have the intended effect

Where I'm stuck / my question(s)

  1. Is my approach on serving static files in 'production' correct? If not, why?
  2. Am I getting my build sequence wrong?
  3. Why does this injection seem to keep happening even if I'm trying to serve static files

My head.blade.php (I'm assuming that in production I just want to serve static files)

@if(!app()->environment('production'))

@vite('resources/css/app.css')

@else

<link rel="preload" href="{{ asset('build/assets/app-e0be5467.css') }}" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="{{ asset('build/assets/app-e0be5467.css') }}"></noscript>

<link rel="preload" href="{{ asset('build/assets/app-1c9978c6.css') }}" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="{{ asset('build/assets/app-1c9978c6.css') }}"></noscript>

@endif

My vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import path from 'path';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/sass/app.scss', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});

My package.json

"scripts": {
    "dev": "vite",
    "build": "vite build && vite build --ssr"
},
0

There are 0 best solutions below