Last active
January 24, 2023 09:52
-
-
Save innocenzi/30e52fdae4f53e9cb72fabfd2b9c79c5 to your computer and use it in GitHub Desktop.
Inertia reload plugin PoC
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
import { createApp, h } from 'vue' | |
import { createInertiaApp, router } from '@inertiajs/vue3' | |
// This virtual import adds the HMR code to the client | |
import 'virtual:inertia/reload' | |
// This persists the router to `window`, can't think of another way unfortunately | |
window.inertia = { router } | |
// Alternatively you could just have the "client code" here, but the packagability would be worse | |
createInertiaApp({ | |
resolve: name => { | |
const pages = import.meta.glob('./Pages/**/*.vue', { eager: true }) | |
return pages[`./Pages/${name}.vue`] | |
}, | |
setup({ el, App, props, plugin }) { | |
createApp({ render: () => h(App, props) }) | |
.use(plugin) | |
.mount(el) | |
}, | |
}) |
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 reloadPlugin() { | |
return { | |
name: 'inertia-reload', | |
resolveId(id) { | |
if (id === 'virtual:inertia/reload') { | |
return '\0virtual:inertia/reload' | |
} | |
}, | |
async load(id) { | |
if (id === '\0virtual:inertia/reload') { | |
// This code will be on the client and will listen to an event | |
// after which it will call "reload" on the router instance | |
return ` | |
if (import.meta.hot) { | |
import.meta.hot.on('inertia:reload', (router) => { | |
window.inertia.router.reload() | |
}) | |
} | |
` | |
} | |
}, | |
configureServer: (server) => { | |
// This part of the code listen for file changes and decides | |
// when to send the custom HMR reload event | |
server.watcher.on('change', async(file) => { | |
// fine tune the logic here, this is just an example | |
if (!file.endsWith('Controller.php')) { | |
return | |
} | |
server.ws.send({ | |
type: 'custom', | |
event: 'inertia:reload', | |
data: router, | |
}) | |
}) | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment