Created
February 11, 2025 09:43
-
-
Save naranyala/7325f9dcef4353592cbede673aa33f40 to your computer and use it in GitHub Desktop.
this is mithril.js file-based routing
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 m from "mithril"; | |
// Auto-import all `.ts` and `.js` files inside `pages/` | |
const modules = import.meta.glob("./pages/**/*.{ts,js}"); | |
import { Layout } from "./layouts/default"; | |
const routes: Record<string, any> = {}; | |
// Define a simple 404 component | |
const NotFound = { | |
view: () => m(Layout, { class: "text-center p-4" }, [ | |
m("h1", { class: "text-2xl font-bold text-red-600" }, "404 - Page Not Found"), | |
m(m.route.Link, { href: "/" }, "Go back home"), | |
]), | |
}; | |
for (const path in modules) { | |
let routePath = path | |
.replace("./pages", "") // Remove base path | |
.replace(/\.(js|ts)$/, "") // Remove file extension | |
.replace(/\[([^\]]+)\]/g, ":$1") // Convert [param].ts → :param | |
.replace(/\/index$/, ""); // Ensure `/sample-page/index.ts` maps to `/sample-page/` | |
// Ensure route starts with `/` | |
if (!routePath.startsWith("/")) { | |
routePath = "/" + routePath; | |
} | |
// Assign route dynamically | |
routes[routePath] = { | |
onmatch: async () => { | |
const module = await modules[path](); | |
return module.default; | |
}, | |
}; | |
} | |
// Add a wildcard 404 route | |
routes["/:404..."] = NotFound; | |
// Initialize Mithril Router | |
export function initRouter() { | |
m.route(document.body, "/", routes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment