为 vite React 项目启用热重载而不是页面重载

Mah*_*ree 16 javascript reactjs vite

我是新来的,我刚刚开始了一个新的反应应用程序。我的项目启用了 hmr(热模块替换)并且没问题。我刚刚添加了一些更改,但是当我现在启动它时,hmr 被禁用,当添加新更改时,浏览器正在重新加载(更新速度不快),并且在终端中记录:我 12:37:54 PM [vite] page reload src/App.tsx 创建了一个新的测试应用程序,它启用了 hmr,当我添加任何更改日志: 12:35:23 PM [vite] hmr update /src/App.tsx (x2) 您能告诉我如何启用 hmr 而不是页面重新加载吗?

这是我的vite.config.ts记录项目page reload

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()]
})
Run Code Online (Sandbox Code Playgroud)

tsconfig.json 适用于记录的项目page reload


{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["./src"]
}
Run Code Online (Sandbox Code Playgroud)

dis*_*rse 26

我的解决方案是确保组件文件名的大小写与导入匹配,因此:

import Login from "../components/Login.vue";
Run Code Online (Sandbox Code Playgroud)

当文件名LogIn.vue导致登录组件未在更改时重新加载时(没有错误)。将导入更改为:

import Login from "../components/LogIn.vue"
Run Code Online (Sandbox Code Playgroud)

解决了问题!

  • 对于未来的谷歌到达:tsconfig.json 有一个字段 `forceConsistentCasingInFileNames` 您想要设置为 `true` (2认同)

Mah*_*ree 16

经过搜索后;我找到了这个链接。问题是,如果任何导出被命名为导出,export const foo = 12这样就会破坏 hmr。所以更改为export default function FooBar(){}hmr 后就可以工作了。


小智 9

就我而言,我使用的是 typescript,解决方案是设置vite.config.jsReact 插件,如 Github 评论中所示:https://github.com/vitejs/vite/discussions/4577#discussioncomment-2320990

基本上是这样的:

export default defineConfig({
  plugins: [
    react({
      include: "**/*.tsx",
    }),
  ],
});
Run Code Online (Sandbox Code Playgroud)


use*_*907 8

要启用热重载,您需要将此配置放在 vite.config.ts 中

export default defineConfig({
  plugins: [react()],
  server: {
    watch: {
      usePolling: true
    }
  }
})
Run Code Online (Sandbox Code Playgroud)


Rok*_*kas 6

我最近遇到了这个问题,这里有一个解决方案。如果您使用.jsx文件,则应该修改vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react({
    // Add this line
    include: "**/*.jsx",
  })]
})

Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的是 typescript ( .tsx),则可以修改vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react({
    // Add this line
    include: "**/*.tsx",
  })]
})

Run Code Online (Sandbox Code Playgroud)

希望这能解决您的问题。

  • 很高兴你成功解决了这个问题,祝你有美好的一天:) (2认同)