Last active
January 1, 2026 14:50
-
-
Save AceCodePt/2a311d84a6283082937e38eaaa230a3f to your computer and use it in GitHub Desktop.
Generate routes for Astro
This file contains hidden or 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 { writeFileSync } from "fs"; | |
| import { globSync } from "glob"; | |
| const apiRoutes = globSync("**/api/**/*.ts", {}); | |
| const pagesRoutes = globSync("**/pages/{/!(api)/[!_]*/,[!_]*/,/}[!_]*.astro", {}); | |
| const constDef = []; | |
| function toConstDef(varName, path) { | |
| if (path.includes("[")) { | |
| const vars = path.match(/(?!\[)[^\[\]]+(?=\])/g); | |
| return `export const ${varName} = (${vars | |
| .map((x) => x + ":string") | |
| .join(",")}) => \`${path.replace( | |
| /\[\[?\.?\.?\.?([^\]]*)\]?\]/g, | |
| "$${$1}", | |
| )}\` as const`; | |
| } | |
| return `export const ${varName} = "${path}";`; | |
| } | |
| apiRoutes.forEach((route) => { | |
| const path = route | |
| .replace(/(src\/pages)/g, "") | |
| .replace(/.ts$/g, ""); | |
| if (!path) { | |
| constDef.push(`export const ROOT_API="/"`); | |
| return; | |
| } | |
| const varName = path.toUpperCase().replace(/[\[\]\/\-.]/g, "_").replace(/^\_/g, ""); | |
| constDef.push(toConstDef(varName, path)); | |
| }); | |
| pagesRoutes.forEach(route => { | |
| const strippedRoute = route.replace(/(src\/pages)|(\.astro)|(index)/g, "").replace(/\/$/g, ""); | |
| if (!strippedRoute) { | |
| constDef.push(`export const PAGE_ROOT="/"`) | |
| return; | |
| } | |
| const varName = "PAGE"+strippedRoute.toUpperCase().replace(/[\[\]\/\-.]/g, "_").replace(/\_$/g, ""); | |
| constDef.push(toConstDef(varName, strippedRoute)) | |
| }) | |
| const template = `/* | |
| * I was generated. DON'T TOUCH ME! | |
| */ | |
| ${constDef.join("\n")} | |
| `; | |
| writeFileSync("./routes.ts", template); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to install glob!
Also you can add to package.json -> scripts: