Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I set up HMR for Vue Single File Components in Vite
    Hot Module Replacement HMR Vue Single File Components Vite Vue Vite plugin development server Vue SFCs HMR setup


How do I set up HMR for Vue Single File Components in Vite


To set up Hot Module Replacement (HMR) for Vue Single File Components (SFCs) in a Vite project, you can follow these steps:

1. Install the required plugin:
- Vite provides a first-party plugin for Vue SFCs called `@vitejs/plugin-vue`. Make sure to install it as a development dependency:


     npm install --save-dev @vitejs/plugin-vue
     

2. Configure the plugin in `vite.config.js`:
- In your project's `vite.config.js` file, import the `vue` plugin and add it to the `plugins` array:

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

     export default defineConfig({
       plugins: [
         vue()
       ]
     })
     

3. Start the development server:
- Run the following command to start the Vite development server with HMR enabled:


     npm run dev
     

That's it! With these steps, Vite will automatically set up HMR for your Vue SFCs. Now, when you make changes to your Vue components, the browser will instantly reflect those changes without a full page reload, preserving the application state.

Here are a few additional notes:

- If you're using TypeScript, you can also install the `@vitejs/plugin-vue-jsx` plugin to get HMR support for Vue JSX components.
- Vite's HMR implementation is designed to work seamlessly with Vue's built-in HMR capabilities, so you don't need to manually configure anything beyond the plugin setup.
- For more advanced HMR customization, you can refer to Vite's HMR API documentation.

By following these steps, you can easily set up HMR for your Vue SFCs in a Vite-powered project, improving the development experience and productivity.

Citations:
[1] https://vitejs.dev/guide/features
[2] https://codewithsusan.com/notes/vuejs-simplified-11
[3] https://stackoverflow.com/questions/73313176/vite-hmr-doesnt-detect-changes-to-components-nested-under-sub-folders
[4] https://github.com/vitejs/vite/discussions/7211
[5] https://v3.vitejs.dev/guide/features