Skip to content

Instantly share code, notes, and snippets.

@kiliman
Created July 6, 2022 13:26
Show Gist options
  • Select an option

  • Save kiliman/9d238aebd0fce58de20878803615f729 to your computer and use it in GitHub Desktop.

Select an option

Save kiliman/9d238aebd0fce58de20878803615f729 to your computer and use it in GitHub Desktop.
Replace param prefix from $ to any character

I created a function that will let you change the param prefix $ to any other character. This is helpful if you use a shell that treats $ as a variable prefix and you need to constantly escape it in your terminal.

Just add this to remix.config. I've imported the default convention, so it will continue to work in the future. This simply replaces your desired prefix with :, which is what Remix expects. Remember, this is the final route definition. The default convention converts $ to :.

You can use any prefix character (I chose ^). It supports catch-all as well as multi-param routes.

// remix.config.js
const {
  defineConventionalRoutes,
} = require("@remix-run/dev/dist/config/routesConvention");

/**
 * @type {import('@remix-run/dev').AppConfig}
 */
module.exports = {
  ignoredRouteFiles: ["**/.*"],
  routes: () => updateParamPrefix("^"),
};

function updateParamPrefix(paramPrefix) {
  const conventionalRoutes = defineConventionalRoutes("app", ["**/.*"]);

  const fixPath = (path) => {
    return path === paramPrefix
      ? "*" // handle catch-all
      : path?.replaceAll(paramPrefix, ":");
  };

  return Object.fromEntries(
    Object.entries(conventionalRoutes).map(([key, route]) => [
      key,
      { ...route, path: fixPath(route.path) },
    ])
  );
}
app/routes
├── ^.tsx
├── ^a.^b.tsx
├── ^param.tsx
├── __layout
│   └── route.tsx
├── __layout.tsx
└── index.tsx
<Routes>
  <Route file="root.tsx">
    <Route file="routes/__layout.tsx">
      <Route path="route" file="routes/__layout/route.tsx" />
    </Route>
    <Route path=":param" file="routes/^param.tsx" />
    <Route path=":a/:b" file="routes/^a.^b.tsx" />
    <Route index file="routes/index.tsx" />
    <Route path="*" file="routes/^.tsx" />
  </Route>
</Routes>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment