Virtual modules with HMR invalidation plugin for Vite
npm install vite-plugin-virtual


> Virtual modules with HMR plugin for Vite
Install Vite Plugin Virtual:
``bash`
$ npm install -D vite-plugin-virtual
Add to your vite.config.js:
`js
import virtual from 'vite-plugin-virtual'
export default {
plugins: [
virtual({
'virtual:module': export default { hello: 'world' },`
'virtual:config': { hello: 'world' }
})
]
}
In your sources you can now import the virtual modules
`js
import obj from 'virtual:config'
console.log(obj)
`
You can update the virtual module during dev
`js
import virtual, { updateVirtualModule } from 'vite-plugin-virtual'
const plugin = virtual({
'virtual:module': export default { hello: 'world' },Hello ${'computed'} world
'virtual:config': { hello: 'world' },
'virtual:lazy': () => ,
})
updateVirtualModule(plugin, 'virtual:config', { hello: 'new message' })
`
You can invalidate the virtual module during dev in case the config changes
`js
import virtual, { invalidateVirtualModule } from 'vite-plugin-virtual'
const modules = {
'virtual:module': export default { hello: 'world' },
'virtual:config': { hello: 'world' }
}
const plugin = virtual(modules)
const server: ViteDevServer
modules['virtual:config'] = { hello: 'new message' }
invalidateVirtualModule(server, 'virtual:config')
`
To enable TypeScript IntelliSense for a virtual module, you can use ambient modules to declare the module in a .d.ts file included by your TS setup:
`ts``
declare module 'virtual:config' {
export const hello: string;
}
For more details refer to the TypeScript docs for ambient modules.
- Adapted logic from @rollup/plugin-virtual
- Project setup adopted from @antfu's Vite plugins
MIT License © 2021 patak-js