Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vite HMR not working . Changing code does not reflect on page until restart vite server #16284

Open
7 tasks done
neodino opened this issue Mar 26, 2024 · 20 comments
Open
7 tasks done
Labels
cannot reproduce The bug cannot be reproduced pending triage

Comments

@neodino
Copy link

neodino commented Mar 26, 2024

Describe the bug

I setup a basic react+ts template and expect HMR to work. But It does not.
When I change some values inside App.tsx / main.tsx or any components, it does not updates in browser.
I'm on macOS m1 using vite 5.2.6 and node 18.

I did setup chokidar simple test to check if events get trigged. It works!

Reproduction

pnpm list
Legend: production dependency, optional only, dev only

dependencies:
@reduxjs/toolkit 2.2.2     globals 14.0.0             react-redux 9.1.0          
antd 5.15.4                lodash 4.17.21             styled-components 6.1.8    
chokidar 3.6.0             react 18.2.0               twin.macro 3.4.1           
flexlayout-react 0.7.15    react-dom 18.2.0           vite 5.2.6                 
fsevents 2.3.3             react-icons 5.0.1          vite-tsconfig-paths 4.3.2  

devDependencies:
@openapitools/openapi-generator-cli 2.13.1  eslint 8.57.0                               
@types/node 20.11.30                        eslint-plugin-react-hooks 4.6.0             
@types/react 18.2.72                        eslint-plugin-react-refresh 0.4.6           
@types/react-dom 18.2.22                    openapi-typescript-codegen 0.25.0           
@typescript-eslint/eslint-plugin 7.4.0      sass 1.72.0                                 
@typescript-eslint/parser 7.4.0             tailwindcss 3.4.1                           
@vitejs/plugin-react 4.2.1                  typescript 5.4.3                

cat index.cjs 
const chokidar = require('chokidar');

// One-liner for current directory
chokidar.watch('**/*.tsx').on('all', (event, path) => {
  console.log(event, path);
});
-------
----
--
add node_modules/.pnpm/@[email protected]/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts
add node_modules/.pnpm/@[email protected]/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts
**change src/components/News/index.tsx**

http://google.com

Steps to reproduce

 npm create vite@latest
✔ Project name: … test-vite
✔ Select a framework: › React
✔ Select a variant: › TypeScript

Scaffolding project in 

Done. Now run:

  cd test-vite
  npm install
  npm run dev

 npm install

added 218 packages, and audited 219 packages in 7s

41 packages are looking for funding
  run `npm fund` for details

System Info

npx envinfo --system --npmPackages '{vite,@vitejs/*,rollup}' --binaries --browsers
Need to install the following packages:
[email protected]
Ok to proceed? (y) y

  System:
    OS: macOS 13.6.5
    CPU: (10) arm64 Apple M1 Pro
    Memory: 169.16 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.19.1 - ~/Library/Caches/fnm_multishells/80450_1711424646646/bin/node
    Yarn: 1.22.18 - /usr/local/bin/yarn
    npm: 10.2.4 - ~/Library/Caches/fnm_multishells/80450_1711424646646/bin/npm
    pnpm: 8.15.5 - ~/Library/pnpm/pnpm
  Browsers:
    Chrome: 123.0.6312.59
    Safari: 17.4
  npmPackages:
    @vitejs/plugin-react: ^4.2.1 => 4.2.1
    vite: ^5.2.0 => 5.2.6

Used Package Manager

npm

Logs

No response

Validations

@alfeg
Copy link

alfeg commented Mar 28, 2024

Seems like not all HMR affected.
In our case - changes to the class/styles are not picked up

@swennemans
Copy link

Are you using Chrome? In that case can you give it a try on FIrefox?

@infinidi4s
Copy link

infinidi4s commented Apr 3, 2024

@swennemans I had this issue in Brave and it does work in Firefox.

Firefox:
image

image

In Brave, I don't get any errors and don't get the [vite] connected. string.

Update: I've restarted the browser for a different reason and now this went away and I can see the refreshed page with no issues.

@HJ-Hao
Copy link

HJ-Hao commented Apr 3, 2024

Same problem, when i change .ts, it dosn't update in browser. I'm on macOS i7 using vite 5.2.0 and node 18.
and After i change vite version to 4.3.1, hmr work.

@VQH-cmd
Copy link

VQH-cmd commented Apr 8, 2024

from: node 20-21 - windows
[email protected] => hmr working.
until 5.2 => broken.

Exactly the doc's setup:
https://vitejs.dev/guide/backend-integration.html

<script type="module">
	import RefreshRuntime from "http://localhost:5173/@react-refresh"
	RefreshRuntime.injectIntoGlobalHook(window)
	window.$RefreshReg$ = () => {}
	window.$RefreshSig$ = () => (type) => type
	window.__vite_plugin_react_preamble_installed__ = true
</script>
<script type="module" src="http://localhost:5173/@vite/client"></script>
<script type="module" src="http://localhost:5173/script/app/client.tsx"></script>

=> Please make the HMR backend work normally as 5.0 !

@James-Wilkinson-git
Copy link

I also have issues with HMR, it appears that HMR wont work if Vite is not installed at the top level of your diretory, I made a sample app in vite-svlte/vite-project, and on initial install HMR worked, closed VS Code and cd into vite-project and HMR no longer works. On Windows 11.

@mark-wiemer
Copy link

I was getting this same issue after creating a project using the vite template with Bun in WSL, but after installing Bun on Windows and running bun install vite --global HMR started working :) ref https://github.com/mark-wiemer/mark-wiemer-com

@qupig
Copy link

qupig commented Jul 7, 2024

Consistent with the test results of @VQH-cmd, the last working version was [email protected], while v5.1.0 and the latest version v5.3.3 are both damaged.

I noticed an interesting phenomenon, HMR works when I test it in Firefox, but once I visit it once with Safari, HMR will fails in both Safari and Firefox, it freezes at the last modification before the Safari visit.

That said, it appears that Safari's request caused the HMR to break and freeze.

@alexelalex
Copy link

alexelalex commented Jul 8, 2024

Downgrading to 5.0.12 didn't solve it for me.
I'm on a Mac M1. I found that it works fine when running in Codespace.

--EDIT--
Updated macOS to Sonoma 14.5
Seems to work fine now

@soletan
Copy link

soletan commented Jul 13, 2024

Stumbling upon this issue no matter what version of Vite I'm using. Tried 5.0.9, tried 5.3.3, tried 4.5.3 ... while developing an application based on Vue. Sometimes I can even break the code severely with neither Vite showing me any severe build error in console nor browser showing me the common warning box overlay ... yes, it happens when testing application in Chrome. But it happens when testing it in Firefox as well.

When entering another line like

console.log( "foo" );

that change isn't picked up at all. I doubt it is even recognized by Vite itself.

UPDATE: Vite seems to pick up the change as it keeps counting up in the console output when writing something like

00:39:44 [vite] hmr update /src/views/input/FightView.vue, /src/views/input/PreparationView.vue (x5)

@epoundor
Copy link

epoundor commented Jul 16, 2024

I have the same issue with a monorepo achitectutre. I tried both Chrome and Firefox even Safari

I even forced HMR by using
server: {
hmr: true
}
on vite config file

@andremarcondesteixeira
Copy link

andremarcondesteixeira commented Aug 3, 2024

I am having the same issue. I use named exports only, classes and typescript, in a react project using the react-typescript-swc template. Whenever I change something, the hot reload is alerted in the console, the browser is refreshed, but the actual code changes are not picked up, thus making hmr essentially useless.

@aabbtree77
Copy link

aabbtree77 commented Aug 18, 2024

Similarly here. Vite and React, npm run dev does not update tailwind changes on Ubuntu 22.04 with Chrome Version 126.0.6478.126 (Official Build), but Firefox 129.0.1 does work perfectly. Also, Chrome at times caches stuff so that it is impossible to update anything in either way: npm run dev, or npm run build followed by npm run preview (both may show some older version of an npm run dev produced say 15 minutes ago). Restarting Chrome, deleting cache with Chrome's GUI clear history, closing Firefox in background does not improve anything. Firefox alone is flawless though.

Vite + React HMR is fully functional in my case. My problem was that I had responsive Tailwind widths and Chrome would not display adjusted elements at the biggest breakpoint 2xl, e.g. 2xl:w-3/5 would not set the element width to 60% despite that 2xl stands for 1536px and I am running Chrome on the screen with 1920x1080. It turns out that there is an Ubuntu desktop bar and Firefox and Chrome treat it differently, Firefox ignores it while Chrome subtracts bar's width from the browser viewport resolution thus not reaching those 1536px, I think.

In any case, my problem was not caching or Vite, though it is useful to know about ctrl+shift+r to reload the page without caching and F12->Network->Disable Cache in Chrome.

@Uriyo
Copy link

Uriyo commented Oct 19, 2024

I am also getting the same issue HMR is not working, even the changes are not being populated after the manual restart and i have tried incogito , removed the cache, and re install the packages the problem still persists.
vite version i am using : VITE v5.4.9
system : macOS m1 chip

@cw222kq
Copy link

cw222kq commented Oct 21, 2024

I also had this HMR issue. In my case, it seemed to be caused by the fact that I was using WSL for development. I ran npm run dev in WSL, but when I opened the browser on my Windows computer, the code changes were not reflected. If anyone is using WSL and doesn’t experience this issue, please share your solution.

Currently, my approach is to develop in the Windows environment, where everything works properly.
Initially, I also had issues in the Windows environment (Windows 11), but after removing the package-lock.json and node_modules folder, and running npm i again, it started working.
I'm using Vite 5.4.9, and this is my vite.config.ts file (I believe it's the default one):

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});

@rubyonrails3
Copy link

So I also ran into the same issue, I have recently upgraded a Ruby on Rails app from 5.1 to 7.2 and I have integrated Vite into my project.

My issue is related to safari, as I have tested Firefox and Chrome and both seem to work without any issue.

If I empty the cache then it works but that is not a good option for me. I have disabled Cache in the network tab as well and that didn't help me either.

So looking for ideas, I prefer working with Safari so if anyone has any workaround that will do as well.

BTW I am on the latest beta of MacOS Sequoia 15.1.

@DanielOrtel
Copy link

DanielOrtel commented Nov 17, 2024

Not sure this is relevant to OP, but if you have access to the underlying server running the local dev server, add this after starting it up:

const hmr = import.meta as any; // if you are averse to using `any`, cast import.meta.hot as ViteHotContext

if (hmr.hot) {
  hmr.hot.on('vite:beforeFullReload', () => {
    logger('[HMR] -'.magenta, 'reloading server...'); // or whatever you want here
    server.close();
  });

  hmr.hot.dispose(() => {
    server.close();
  });
}

This fixed all HMR related issues for me.

@alan-mroczek
Copy link

alan-mroczek commented Dec 6, 2024

I was able to resolve my issues by adding server in my vite.config.ts:

export default defineConfig({
  plugins: [react()],
  server: {
    watch: {
      usePolling: true
    }
  }
})

Why exactly? No idea, found it on the internet 🤷

Edit: well, documentation explains it pretty clearly:

When running Vite on WSL2, file system watching does not work when a file is edited by Windows applications (non-WSL2 process). This is due to a WSL2 limitation. This also applies to running on Docker with a WSL2 backend.

@aleclarson
Copy link
Member

aleclarson commented Dec 29, 2024

I experienced this on macOS Sequoia 15.2 and @alan-mroczek's solution worked.

edit: This could be related to my code being on a removable volume, in my case. Though I have not confirmed this yet.

@SwizzleKen
Copy link

Not sure if this will help anyone else, but in my case I was working with TanStack router and had the code below.

My index route was hot reloading just fine, though, so I started to look at what the differences were. I found that removing the export on the export function SignIng() (which wasn't necessary anyway) suddenly made the HMR start working again.

import { useAuthActions } from '@convex-dev/auth/react'
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/auth')({
  component: SignIn,
  notFoundComponent: () => {
    return <p>Something not found in index!</p>
  },
})

export function SignIn() { // <== Remove this export and the HMR starts working again!
  const { signIn } = useAuthActions()
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault()
        const formData = new FormData(event.currentTarget)
        formData.append('redirectTo', '/success')
        void signIn('resend', formData)
      }}
    >
      <input name='email' placeholder='Email' type='text' />
      <button type='submit'>Send sign-in link</button>
    </form>
  )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cannot reproduce The bug cannot be reproduced pending triage
Projects
None yet
Development

No branches or pull requests