Last active
February 11, 2024 01:34
-
-
Save DanielBaulig/0ed6ce6179e898d0ea08a425f978472b to your computer and use it in GitHub Desktop.
How to hot reload a virtual module in a Vite plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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