Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: update route configs on file add / delete
- Loading branch information
Showing
4 changed files
with
122 additions
and
99 deletions.
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import type { Plugin } from 'vite' | ||
import { compile, match } from 'path-to-regexp' | ||
import type { SiteConfig, UserConfig } from '../config' | ||
|
||
export function resolveRewrites( | ||
pages: string[], | ||
userRewrites: UserConfig['rewrites'] | ||
) { | ||
const rewriteEntries = Object.entries(userRewrites || {}) | ||
const rewrites = rewriteEntries.length | ||
? Object.fromEntries( | ||
pages | ||
.map((src) => { | ||
for (const [from, to] of rewriteEntries) { | ||
const dest = rewrite(src, from, to) | ||
if (dest) return [src, dest] | ||
} | ||
}) | ||
.filter((e) => e != null) as [string, string][] | ||
) | ||
: {} | ||
return { | ||
map: rewrites, | ||
inv: Object.fromEntries(Object.entries(rewrites).map((a) => a.reverse())) | ||
} | ||
} | ||
|
||
function rewrite(src: string, from: string, to: string) { | ||
const urlMatch = match(from) | ||
const res = urlMatch(src) | ||
if (!res) return false | ||
const toPath = compile(to) | ||
return toPath(res.params) | ||
} | ||
|
||
export const rewritesPlugin = (config: SiteConfig): Plugin => { | ||
return { | ||
name: 'vitepress:rewrites', | ||
configureServer(server) { | ||
// dev rewrite | ||
server.middlewares.use((req, _res, next) => { | ||
if (req.url) { | ||
const page = req.url | ||
.replace(/[?#].*$/, '') | ||
.slice(config.site.base.length) | ||
if (config.rewrites.inv[page]) { | ||
req.url = req.url.replace(page, config.rewrites.inv[page]!) | ||
} | ||
} | ||
next() | ||
}) | ||
} | ||
} | ||
} |