Dynamic loading of Vue CSS assets with Vite

I've been experimenting with switching from Webpack to Vite, because when developing with Vite it's really fast and you get some nice features like Hot Module Reloading (HMR), so that when you're editing a Vue component and save the file, you instantly see the results in your browser window without having to reload the page.

I've been using Vite with the Backend Integration instructions, and on a Laravel Lumen site one problem I had was that while Vite worked great for development - when I did a production build I found the CSS from the Vue SFCs (Single File Components) weren't being injected into the <head> the way the were when running in development mode. Basically my page would be there but totally unstyled.

I had another Vite site that worked totally fine with the production build (this one), and it took a while to figure out what the difference was.

Ultimately I realized the working site had as part of its JS build, some code from vite called preload-helper, which seems to be responsible for injecting stylesheets into the page. My other site wasn't including the preload-helper, and it seems the difference was that the 2nd site wasn't using the dynamic JS import(), feature (because it was such a simple site)

Once I recoded my entrypoint to dynamically import my Vue3 root component like this:

import { createApp } from 'vue'

import('./App.vue')
    .then(({ default: rootComponent }) => {
        const app = createApp(rootComponent);
        app.mount('#app');
    });

then the build included the preload-helper and everything works as expected.

Without this type of loading, a person would have to configure Vite to enable generation of manifest.json, and figure out which CSS file to reference in your page's HEAD, similar to how you figure out the JS to load (because of doing Backend Integration). However at the moment the manifest.json doesn't include the name of the generated CSS file - I filed a Github Issue about it.