Skip to content

Instantly share code, notes, and snippets.

@innocenzi
Last active January 24, 2023 09:52
Show Gist options
  • Save innocenzi/30e52fdae4f53e9cb72fabfd2b9c79c5 to your computer and use it in GitHub Desktop.
Save innocenzi/30e52fdae4f53e9cb72fabfd2b9c79c5 to your computer and use it in GitHub Desktop.
Inertia reload plugin PoC
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)
},
})
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