Skip to content

Instantly share code, notes, and snippets.

@AceCodePt
Last active January 1, 2026 14:50
Show Gist options
  • Select an option

  • Save AceCodePt/2a311d84a6283082937e38eaaa230a3f to your computer and use it in GitHub Desktop.

Select an option

Save AceCodePt/2a311d84a6283082937e38eaaa230a3f to your computer and use it in GitHub Desktop.
Generate routes for Astro
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);
@AceCodePt
Copy link
Author

AceCodePt commented Jan 2, 2024

Don't forget to install glob!

npm i -D glob

Also you can add to package.json -> scripts:

"gen:routes": "node ./generate-routes.mjs"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment