Search code examples
vitewindows-subsystem-for-linuxhmr

Browser not updating with Vite HMR on WSL2


I have WSL2 (Ubuntu) set up on my machine. And I'm working on an OctoberCMS/Laravel website that has Vite setup with HMR. To load my assets on the page im using OFFLINE's vite plugin for OctoberCMS.

Vite is working in the sense that assets are loaded on the page, and when I make changes to files they're reflected in Terminal. 9:52:03 AM [vite] page reload layouts/form.htm

The problem I'm having is that I still have to refresh my browser to see the changes.

Here's what I've tried so far

  • With and without usePolling set
  • With and without host: 0.0.0.0 in my server config (I'm not sure why. I'm not a server guy and that's what I have on my work machine that works fine)
  • Setting the hmr host to 127.0.0.1
  • Setting generateResolveConf=false in /etc/wsl.conf and adding nameserver 1.1.1.1 in my /etc/resolv.conf in WSL (Again, I don't know why - this is how my work machine is setup that works)

When I start vite I get this in my Terminal

  VITE v5.2.9  ready in 185 ms

  ➜  Local:   https://localhost:5173/themes/albums/assets/build/
  ➜  Network: https://172.31.16.20:5173/themes/albums/assets/build/
  ➜  Network: https://172.18.0.1:5173/themes/albums/assets/build/
  ➜  Network: https://172.19.0.1:5173/themes/albums/assets/build/
  ➜  press h + enter to show help

The main difference I see between my PC and work laptop is that the second line gives a 192. IP address on my work laptop (that works).

Like I've mentioned - I'm not a server or network guy so ports and dns etc.. is all a bit over my head.

Here's my vite config if it helps

import { defineConfig } from 'vite'
import { resolve } from 'path'
import fs from 'fs'

const input = {
    css: resolve(__dirname, 'resources/css/app.css'),
    js: resolve(__dirname, 'resources/js/app.js')
}

export default defineConfig({
    base: '/themes/albums/assets/build/',
    publicDir: 'assets/static',
    build: {
        rollupOptions: { input },
        manifest: true,
        emptyOutDir: true,
        outDir: resolve(__dirname, 'assets/build'),
        assetsDir: '',
    },
    server: {
        host: '0.0.0.0',
        https: {
            key: fs.existsSync('/ca/localhost-key.pem') ? fs.readFileSync('/ca/localhost-key.pem', 'utf-8') : '',
            cert: fs.existsSync('/ca/localhost.pem') ? fs.readFileSync('/ca/localhost.pem', 'utf-8') : '',
        },
        hmr: {
            host: 'localhost'
        },
        watch: {
            usePolling: true
        }
    }
});

If anyone has a solution to my problem, and can help me get HMR working would be greatly appreciated. Thanks


Solution

  • I was missing a step that's documented in OFFLINE's vite plugin. And that's including the {% scripts %} tag on the page. The plugin adds some JavaScript to the page thats needed for the reloads to work as expected.