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.
65 lines (63 loc) • 2.19 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
RouterBuilder: () => RouterBuilder
});
module.exports = __toCommonJS(index_exports);
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);
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
RouterBuilder
});