There is a special route in Vite (+ SvelteKit) /__open-in-editor?file=SOURCE-FILE-PATH
that opens the source file in an editor (like VS Code.)
Is it possible to override this route? I would like to wrap this route with some extra logic like automatically closing the browser tab that was opened.
I believe this middleware is what handles the route in question.
I tried making an /__open_in_editor
route in SvelteKit, but it is never called because Vite's launchEditorMiddleware is run first.
My current work-around is to just make another Kit route /__open
. However I would prefer using the same route so that if the /__open_in_editor
route is not implemented in SvelteKit, the default Vite middleware is used instead.
A custom vite plugin that handles the __open-in-editor
route is processed before the internal middleware:
The configureServer hook is called before internal middlewares are installed, so the custom middlewares will run before internal middlewares by default.
Commit that added my vite plugin.
Relevant source:
// open-in-editor.ts
return {
name: 'open-in-editor',
configureServer(server) {
server.middlewares.use('/__open-in-editor', (req, res) => {
const { file } = url.parse(req.url || '', true).query || {}
if (!file) {
res.statusCode = 500
res.end(`launch-editor-middleware: required query param "file" is missing.`)
} else {
res.statusCode = 222
launch(path.resolve(srcRoot, file as string), specifiedEditor, onErrorCallback)
res.end('<p>You may safely close this window.</p><script>window.close()</script>')
}
})
},
}
// vite.config.ts
export default defineConfig({
plugins: [sveltekit(), openInEditorPlugin()],
})