Skip to content

Type-safe href #12994

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/dull-balloons-boil.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
"@react-router/dev": patch
"react-router": patch
---

Fix typegen for repeated params

In React Router, path parameters are keyed by their name.
So for a path pattern like `/a/:id/b/:id?/c/:id`, the last `:id` will set the value for `id` in `useParams` and the `params` prop.
For example, `/a/1/b/2/c/3` will result in the value `{ id: 3 }` at runtime.

Previously, generated types for params incorrectly modeled repeated params with an array.
So `/a/1/b/2/c/3` generated a type like `{ id: [1,2,3] }`.

To be consistent with runtime behavior, the generated types now correctly model the "last one wins" semantics of path parameters.
So `/a/1/b/2/c/3` now generates a type like `{ id: 3 }`.
5 changes: 5 additions & 0 deletions .changeset/khaki-rocks-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@react-router/dev": patch
---

Fix `ArgError: unknown or unexpected option: --version` when running `react-router --version`
20 changes: 20 additions & 0 deletions .changeset/three-eyes-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
"@react-router/dev": patch
"react-router": patch
---

New type-safe `href` utility that guarantees links point to actual paths in your app

```tsx
import { href } from "react-router";

export default function Component() {
const link = href("/blog/:slug", { slug: "my-first-post" });
return (
<main>
<Link to={href("/products/:id", { id: "asdf" })} />
<NavLink to={href("/:lang?/about", { lang: "en" })} />
</main>
);
}
```
174 changes: 174 additions & 0 deletions integration/cli-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { spawnSync } from "node:child_process";
import * as path from "node:path";

import { expect, test } from "@playwright/test";
import dedent from "dedent";
import semver from "semver";
import fse from "fs-extra";

import { createProject } from "./helpers/vite";

const nodeBin = process.argv[0];
const reactRouterBin = "node_modules/@react-router/dev/dist/cli/index.js";

const run = (command: string[], options: Parameters<typeof spawnSync>[2]) =>
spawnSync(nodeBin, [reactRouterBin, ...command], options);

const helpText = dedent`
react-router

Usage:
$ react-router build [projectDir]
$ react-router dev [projectDir]
$ react-router routes [projectDir]

Options:
--help, -h Print this help message and exit
--version, -v Print the CLI version and exit
--no-color Disable ANSI colors in console output
\`build\` Options:
--assetsInlineLimit Static asset base64 inline threshold in bytes (default: 4096) (number)
--clearScreen Allow/disable clear screen when logging (boolean)
--config, -c Use specified config file (string)
--emptyOutDir Force empty outDir when it's outside of root (boolean)
--logLevel, -l Info | warn | error | silent (string)
--minify Enable/disable minification, or specify minifier to use (default: "esbuild") (boolean | "terser" | "esbuild")
--mode, -m Set env mode (string)
--profile Start built-in Node.js inspector
--sourcemapClient Output source maps for client build (default: false) (boolean | "inline" | "hidden")
--sourcemapServer Output source maps for server build (default: false) (boolean | "inline" | "hidden")
\`dev\` Options:
--clearScreen Allow/disable clear screen when logging (boolean)
--config, -c Use specified config file (string)
--cors Enable CORS (boolean)
--force Force the optimizer to ignore the cache and re-bundle (boolean)
--host Specify hostname (string)
--logLevel, -l Info | warn | error | silent (string)
--mode, -m Set env mode (string)
--open Open browser on startup (boolean | string)
--port Specify port (number)
--profile Start built-in Node.js inspector
--strictPort Exit if specified port is already in use (boolean)
\`routes\` Options:
--config, -c Use specified Vite config file (string)
--json Print the routes as JSON
\`reveal\` Options:
--config, -c Use specified Vite config file (string)
--no-typescript Generate plain JavaScript files
\`typegen\` Options:
--watch Automatically regenerate types whenever route config (\`routes.ts\`) or route modules change

Build your project:

$ react-router build

Run your project locally in development:

$ react-router dev

Show all routes in your app:

$ react-router routes
$ react-router routes my-app
$ react-router routes --json
$ react-router routes --config vite.react-router.config.ts

Reveal the used entry point:

$ react-router reveal entry.client
$ react-router reveal entry.server
$ react-router reveal entry.client --no-typescript
$ react-router reveal entry.server --no-typescript
$ react-router reveal entry.server --config vite.react-router.config.ts

Generate types for route modules:

$ react-router typegen
$ react-router typegen --watch
`;

test.describe("cli", () => {
test("--help", async () => {
const cwd = await createProject();
const { stdout, stderr, status } = run(["--help"], {
cwd,
env: {
NO_COLOR: "1",
},
});
expect(stdout.toString().trim()).toBe(helpText);
expect(stderr.toString()).toBe("");
expect(status).toBe(0);
});

test("--version", async () => {
const cwd = await createProject();
let { stdout, stderr, status } = run(["--version"], { cwd });
expect(semver.valid(stdout.toString().trim())).not.toBeNull();
expect(stderr.toString()).toBe("");
expect(status).toBe(0);
});

test("routes", async () => {
const cwd = await createProject();
let { stdout, stderr, status } = run(["routes"], { cwd });
expect(stdout.toString().trim()).toBe(dedent`
<Routes>
<Route file="root.tsx">
<Route index file="routes/_index.tsx" />
</Route>
</Routes>
`);
expect(stderr.toString()).toBe("");
expect(status).toBe(0);
});

test.describe("reveal", async () => {
test("generates entry.{server,client}.tsx in the app directory", async () => {
const cwd = await createProject();
let entryClientFile = path.join(cwd, "app", "entry.client.tsx");
let entryServerFile = path.join(cwd, "app", "entry.server.tsx");

expect(fse.existsSync(entryServerFile)).toBeFalsy();
expect(fse.existsSync(entryClientFile)).toBeFalsy();

run(["reveal"], { cwd });

expect(fse.existsSync(entryServerFile)).toBeTruthy();
expect(fse.existsSync(entryClientFile)).toBeTruthy();
});

test("generates specified entries in the app directory", async () => {
const cwd = await createProject();

let entryClientFile = path.join(cwd, "app", "entry.client.tsx");
let entryServerFile = path.join(cwd, "app", "entry.server.tsx");

expect(fse.existsSync(entryServerFile)).toBeFalsy();
expect(fse.existsSync(entryClientFile)).toBeFalsy();

run(["reveal", "entry.server"], { cwd });
expect(fse.existsSync(entryServerFile)).toBeTruthy();
expect(fse.existsSync(entryClientFile)).toBeFalsy();
fse.removeSync(entryServerFile);

run(["reveal", "entry.client"], { cwd });
expect(fse.existsSync(entryClientFile)).toBeTruthy();
expect(fse.existsSync(entryServerFile)).toBeFalsy();
});

test("generates entry.{server,client}.jsx in the app directory with --no-typescript", async () => {
const cwd = await createProject();
let entryClientFile = path.join(cwd, "app", "entry.client.jsx");
let entryServerFile = path.join(cwd, "app", "entry.server.jsx");

expect(fse.existsSync(entryServerFile)).toBeFalsy();
expect(fse.existsSync(entryClientFile)).toBeFalsy();

run(["reveal", "--no-typescript"], { cwd });

expect(fse.existsSync(entryServerFile)).toBeTruthy();
expect(fse.existsSync(entryClientFile)).toBeTruthy();
});
});
});
7 changes: 1 addition & 6 deletions integration/helpers/vite-5-template/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
{
"include": [
"env.d.ts",
"**/*.ts",
"**/*.tsx",
".react-router/types/**/*.d.ts"
],
"include": ["env.d.ts", "**/*.ts", "**/*.tsx", ".react-router/types/**/*"],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"verbatimModuleSyntax": true,
Expand Down
7 changes: 1 addition & 6 deletions integration/helpers/vite-6-template/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
{
"include": [
"env.d.ts",
"**/*.ts",
"**/*.tsx",
".react-router/types/**/*.d.ts"
],
"include": ["env.d.ts", "**/*.ts", "**/*.tsx", ".react-router/types/**/*"],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"verbatimModuleSyntax": true,
Expand Down
2 changes: 1 addition & 1 deletion integration/helpers/vite-cloudflare-template/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"include": ["env.d.ts", "**/*.ts", "**/*.tsx"],
"include": ["env.d.ts", "**/*.ts", "**/*.tsx", ".react-router/types/**/*"],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"types": ["vite/client"],
Expand Down
92 changes: 87 additions & 5 deletions integration/typegen-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,42 @@ test.describe("typegen", () => {
import { type RouteConfig, route } from "@react-router/dev/routes";

export default [
route("repeated-params/:id/:id?/:id", "routes/repeated-params.tsx")
route("only-required/:id/:id", "routes/only-required.tsx"),
route("only-optional/:id?/:id?", "routes/only-optional.tsx"),
route("optional-then-required/:id?/:id", "routes/optional-then-required.tsx"),
route("required-then-optional/:id/:id?", "routes/required-then-optional.tsx"),
] satisfies RouteConfig;
`,
"app/routes/repeated-params.tsx": tsx`
"app/routes/only-required.tsx": tsx`
import type { Expect, Equal } from "../expect-type"
import type { Route } from "./+types/repeated-params"
import type { Route } from "./+types/only-required"
export function loader({ params }: Route.LoaderArgs) {
type Test = Expect<Equal<typeof params.id, string>>
return null
}
`,
"app/routes/only-optional.tsx": tsx`
import type { Expect, Equal } from "../expect-type"
import type { Route } from "./+types/only-optional"
export function loader({ params }: Route.LoaderArgs) {
type Test = Expect<Equal<typeof params.id, string | undefined>>
return null
}
`,
"app/routes/optional-then-required.tsx": tsx`
import type { Expect, Equal } from "../expect-type"
import type { Route } from "./+types/optional-then-required"
export function loader({ params }: Route.LoaderArgs) {
type Test = Expect<Equal<typeof params.id, string>>
return null
}
`,
"app/routes/required-then-optional.tsx": tsx`
import type { Expect, Equal } from "../expect-type"
import type { Route } from "./+types/required-then-optional"

export function loader({ params }: Route.LoaderArgs) {
type Expected = [string, string | undefined, string]
type Test = Expect<Equal<typeof params.id, Expected>>
type Test = Expect<Equal<typeof params.id, string>>
return null
}
`,
Expand Down Expand Up @@ -362,4 +388,60 @@ test.describe("typegen", () => {
expect(proc.stderr.toString()).toBe("");
expect(proc.status).toBe(0);
});

test("href", async () => {
const cwd = await createProject({
"vite.config.ts": viteConfig,
"app/expect-type.ts": expectType,
"app/routes.ts": tsx`
import path from "node:path";
import { type RouteConfig, route } from "@react-router/dev/routes";

export default [
route("no-params", "routes/no-params.tsx"),
route("required-param/:req", "routes/required-param.tsx"),
route("optional-param/:opt?", "routes/optional-param.tsx"),
route("/leading-and-trailing-slash/", "routes/leading-and-trailing-slash.tsx"),
route("some-other-route", "routes/some-other-route.tsx"),
] satisfies RouteConfig;
`,
"app/routes/no-params.tsx": tsx`
export default function Component() {}
`,
"app/routes/required-param.tsx": tsx`
export default function Component() {}
`,
"app/routes/optional-param.tsx": tsx`
export default function Component() {}
`,
"app/routes/leading-and-trailing-slash.tsx": tsx`
export default function Component() {}
`,
"app/routes/some-other-route.tsx": tsx`
import { href } from "react-router"

// @ts-expect-error
href("/does-not-exist")

href("/no-params")

// @ts-expect-error
href("/required-param/:req")
href("/required-param/:req", { req: "hello" })

href("/optional-param/:opt?")
href("/optional-param/:opt?", { opt: "hello" })

href("/leading-and-trailing-slash")
// @ts-expect-error
href("/leading-and-trailing-slash/")

export default function Component() {}
`,
});
const proc = typecheck(cwd);
expect(proc.stdout.toString()).toBe("");
expect(proc.stderr.toString()).toBe("");
expect(proc.status).toBe(0);
});
});
Loading