Skip to content

Instantly share code, notes, and snippets.

@DanielBaulig
Last active February 11, 2024 01:34
Show Gist options
  • Save DanielBaulig/0ed6ce6179e898d0ea08a425f978472b to your computer and use it in GitHub Desktop.
Save DanielBaulig/0ed6ce6179e898d0ea08a425f978472b to your computer and use it in GitHub Desktop.
How to hot reload a virtual module in a Vite plugin
function vitePlugin() {
const virtualModuleDependency = 'virtual-module-conf.json';
const virtualModuleId = 'virtual:module';
const resolveVirtualId = (id) => '\0' + id;
let virtualModuleContent;
async function refreshVirtualModuleContent(reader) {
const json = JSON.parse(await reader());
virtualModuleContent = `export default ${JSON.stringify(json.value)};`;
}
async function loadVirtualModule() {
await refreshVirtualModuleContent(fs.readFile.bind(fs, virtualModuleDependecy));
return virtualModuleContent;
}
return {
name: 'vite-plugin',
resolveId(id) {
if (id === virtualModuleId) {
return resolveVirtualId(virtualModuleId);
}
},
load(id) {
if (id === resolveVirtualId(virtualModuleId)) {
return loadVirtualModule();
}
},
handleHotUpdate({server, file, modules, read}) {
if (!file.endsWith(virtualModuleDependency) {
return modules;
}
refreshVirtualModuleContent(read);
const virtualModule = server.moduleGraph.getModuleById(
resolveVirtualId(virtualModuleId)
);
return [...modules, virtualModule];
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment