Skip to content

Instantly share code, notes, and snippets.

@diboune
Last active August 29, 2023 00:53
Show Gist options
  • Save diboune/06468f8637c271614d1ad8d24c5f655b to your computer and use it in GitHub Desktop.
Save diboune/06468f8637c271614d1ad8d24c5f655b to your computer and use it in GitHub Desktop.
Remix routes id as an array
// 1. copy and paste this in a remix project base directory.
// 2. run `node routes_gen.mjs <optional routes folder default to "./app/routes"> <optional output file default to "./app/routes.ts">`
// 3. you get a cool string[] of all the routes ids in a file inside your project
import fs from "fs";
import path from "path";
const routesFolder = process.argv[2] || "./app/routes/";
const outputFile = process.argv[3] || "./app/routes.ts";
const generateRoutes = (routesFolder, outputFile) => {
fs.readdir(routesFolder, { withFileTypes: true }, (err, entries) => {
if (err) {
console.error("Error reading route files:", err);
return;
}
const routeIds = [
"root",
...entries.map((entry) => {
const { name } = entry;
if (entry.isDirectory()) {
return `routes/${name}`;
} else {
const { name: fileName } = path.parse(name);
return `routes/${fileName}`;
}
}),
];
const exportStatement = `export const routes = ${JSON.stringify(
routeIds
)} as const;\n`;
fs.writeFile(outputFile, exportStatement, (writeErr) => {
if (writeErr) {
console.error("Error writing to output file:", writeErr);
return;
}
console.log("Output file created:", outputFile);
});
});
};
generateRoutes(routesFolder, outputFile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment