Asp.net 4.8 MVC + Vite + Svelte TS + HMR?

Viewed 691

I have a legacy application built in ASP.NET 4.8 MVC. I would like to start building some client side features in Svelte - having svelte components rendering inside razor views. This I have working. I can render a svelte component anywhere in the razor page. However vite has some problem (im guessing with HMR?), and it keeps refreshing the razor page (https://localhost:44300/somefeature) every few seconds.

Environment

asp.net 4.8 mvc loads to https://localhost:44300/
vite is loading on http://localhost:3000/

Here is what i have so far. I ran npm init vite@latest -> selected svelte + svelte TS

vite.config.js

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    svelte({
      compilerOptions: {
        customElement: true,
      }
    })
  ],
  build:{
    // generate manifest.json in outDir
    manifest: true,
    rollupOptions: {
      // overwrite default .html entry
      input: '/src/main.ts'
    }
  }
})

Then i followed the instructions here https://vitejs.dev/guide/backend-integration.html and added this to the razor page:

@Html.Raw("<script type='module' src='http://localhost:3000/@vite/client'></script>")
<script type="module" src="http://localhost:3000/src/main.ts"></script>

(Note - had to use Html.Raw because it wouldnt let me escape the @ correctly - even with @@)
At this point it is rendering my Svelte component perfectly.
The issue however is that vite is now reloading my page every 2 seconds or so - im guessing because HMR is no longer working correctly as the console just says: [vite] connecting...

Can anyone point me in a direction either to get HMR working whilst using another Backend server? For some reason it works in asp.net core, but not so in ASP.NET 4.8. Any observations to help?
Thanks in advance!

1 Answers

Ok i got it working. Here is my vite.config.js. Pay special attention to the input, outDir and server nodes, and adjust them to your scenario. The proxy is important, you can either set it to your https or http mvc endpoint and port that asp.net spins up for you.

Here is the config:

export default defineConfig({
  plugins: [
    svelte()
  ],
  build:{
    // generate manifest.json in outDir
    manifest: true,
    rollupOptions: {
      // overwrite default .html entry
      input: 'Scripts/svelte/app.js',
    },
    outDir: 'Scripts/svelte/dist'
  },
  server: {
    proxy:{
      '*' : {
        target: 'http://localhost:26688',
        changeOrigin: true
      }
    },
    hmr: {
      protocol: 'ws'
    }
  }
})

Its pretty cool - you get instant HMR of any svelte component inside a razor page without losing any razor state.

Related