Serving .js and .css from Vite + Svelte to a static website

I have a pre-existing website using a popular website builder.

I want to be able to inject interactive svelte components on certain blog pages to help demonstrate concepts.

I got a rough prototype working with Vite + Svelte, but I’m wondering how I can improve upon it, specifically with Hot Module Reloading so I don’t have to refresh the page every time to see the updated Svelte component.

From a barebones Vite Svelte template, I made the following modifications to vite.config.ts:

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

// https://vite.dev/config/
export default defineConfig({
  plugins: [svelte()],
  build: {
    manifest: true,
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].js`,
        chunkFileNames: `assets/[name].js`,
        assetFileNames: `assets/[name].[ext]`
      }
    }
  }
})

When I run my build command, the filenames are no longer hashed so I can access them without updating URLs. If I enable my local web server I now get more permanent URLs to the JS and CSS files.

In my website builder, I can now develop and use the svelte component like so:

<script type="module" crossorigin src="http://127.0.0.1:5500/dist/assets/index.js"></script>
<link rel="stylesheet" crossorigin href="http://127.0.0.1:5500/dist/assets/index.css" />

(Eventually this code will be served from CDN but for now I want to be able to develop from my local machine)

In my website builder, I just give a div the proper id (I’m using counter) and update the main.ts file accordingly:

import { mount } from 'svelte'
import App from './App.svelte'

const app = mount(App, {
  target: document.getElementById('counter')!,
})

export default app

Basically, I’m trying to build out a good workflow to inject small Svelte apps into my existing website. Vite seems to default to bundling everything inside index.html, but I’m looking to override that behavior, and inject the .js and .css into the html files built by my website builder. I think the adding HMR would really take this workflow to the next level, but I can’t figure out how to do that with my current setup.