首页  >  问答  >  正文

Vite HMR 无法检测子文件夹内组件的更改

在 Vue + Vite 项目中,我有这样的文件夹结构

问题是 vite 无法检测 A.vue 或 B.vue 中的更改(ctrl+s),即嵌套在组件文件夹中的 NestedFolder 下的组件。其他地方都工作正常。

我的 vite.config.js 看起来像这样,

import { fileURLToPath, URL } from 'node:url'

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue()
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      '@public': fileURLToPath(new URL('./public', import.meta.url))
    }
  },
  server: {
    proxy: {
      '/api': {
        target: 'XXX',
        changeOrigin: true,
        secure: false,      
        ws: true,
      }
    }
  }
})

我已经按照 vite HMR API 文档尝试了自定义 HMR 函数,让它使用它发送完全重新加载。

...
plugins: [
    vue(),
    {
      name: 'custom-hmr',
      enforce: 'post',
      // HMR
      handleHotUpdate({ file, server }) {
        if (file.endsWith('.vue')) {
          console.log('reloading json file...');
  
          server.ws.send({
            type: 'reload',          
            path: '*'
          });
        }
      },
    }
  ], ...

我查看了 vite 的 HMR API 文档,但不知道如何在使用自定义 hmr 函数时向 vite 发送更新事件

任何有关如何解决此问题的帮助/建议将不胜感激。

P粉854119263P粉854119263320 天前587

全部回复(1)我来回复

  • P粉412533525

    P粉4125335252023-11-05 00:40:17

    好的,我解决了这个问题。问题不在于嵌套文件夹。 Vite似乎会忽略使用绝对路径导入的组件。

    例如Vite 不会检测导入组件的更改:

    import Dropdown from '@/components/GlobalDropdown.vue'
    //@ resolves to /src

    但检测相对导入的变化:

    import LoadingSpinner from '../LoadingSpinner.vue'

    我找不到任何可以解决此问题的设置。但是组件导入的相对路径解决了这个问题。这是一个问题吗?

    回复
    0
  • 取消回复