UNPKG

waanverse-react-routes

Version:

A lightweight and customizable route management library for React applications using React Router. This library allows you to define and extend route names while ensuring TypeScript autocompletion.

40 lines (39 loc) 1.18 kB
// src/index.ts var RouterBuilder = class { routes = []; // Method to add a new route with type safety addRoute(route) { this.routes.push(route); return this; } // Finalize route configuration build() { return this.routes; } // Utility function for path parameter replacement replaceParams(path, params) { if (!params) return path; return path.replace(/:([a-zA-Z_]+)/g, (_, key) => { if (params[key] !== void 0) { return String(params[key]); } throw new Error(`Missing required param: ${key}`); }); } // Utility function for adding query parameters addQueryParams(path, query) { if (!query || Object.keys(query).length === 0) return path; const queryString = new URLSearchParams(query).toString(); return `${path}?${queryString}`; } // Generic path getter with type safety getPath(name, params, query) { const route = this.routes.find((route2) => route2.name === name); if (!route) throw new Error(`Route "${name}" not found`); const finalPath = this.replaceParams(route.path, params); return this.addQueryParams(finalPath, query); } }; export { RouterBuilder };