> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# TanStack Router

现代化且可扩展的 React 应用路由解决方案。

ReactLynx 支持 [Memory Routing](https://tanstack.com/router/latest/docs/framework/react/guide/history-types#memory-routing) 和 [File-Based Routing](https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing)，
其中 Memory Routing 是必需的，因为 Lynx 中存在浏览器 [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) 限制，
而 File-Based Routing 通过 Rspeedy 无缝集成 `@tanstack/router-plugin/rspack` 来启用。

### 安装依赖

安装 dependencies：


```sh [npm]
npm install @tanstack/react-router url-search-params-polyfill
```

```sh [yarn]
yarn add @tanstack/react-router url-search-params-polyfill
```

```sh [pnpm]
pnpm add @tanstack/react-router url-search-params-polyfill
```

```sh [bun]
bun add @tanstack/react-router url-search-params-polyfill
```

```sh [deno]
deno add npm:@tanstack/react-router npm:url-search-params-polyfill
```

安装 devDependencies：


```sh [npm]
npm install @tanstack/router-plugin -D
```

```sh [yarn]
yarn add @tanstack/router-plugin -D
```

```sh [pnpm]
pnpm add @tanstack/router-plugin -D
```

```sh [bun]
bun add @tanstack/router-plugin -D
```

```sh [deno]
deno add npm:@tanstack/router-plugin -D
```

### 项目配置

- **File-based Routing**: 通过 `@tanstack/router-plugin/rspack` 实现。
- **React 18 API 兼容性**: 使用 `@lynx-js/react/compat` 确保第三方库正常工作。


❓ 为什么使用 @lynx-js/react/compat

ReactLynx 通过 `@lynx-js/react/compat` 提供 React 18 API 兼容， 提供 TanStack
Router 所需的 API，如 `React.startTransition`。

```js title=lynx.config.js
import { defineConfig } from '@lynx-js/rspeedy';
import { tanstackRouter } from '@tanstack/router-plugin/rspack';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);

export default defineConfig({
  // ...其它的配置
  source: {
    alias: {
      react$: require.resolve('@lynx-js/react/compat'),
    },
  },
  tools: {
    rspack: {
      plugins: [
        tanstackRouter({
          target: 'react',
        }),
      ],
    },
  },
});
```

### 路由配置

在 Lynx 环境中，[document](https://developer.mozilla.org/en-US/docs/Web/API/Document) 为 `undefined`，导致错误地被识别为 `isServer: true`。你需要显式设置 `isServer: false` 来确保渲染的正确性。

此外，由于 Lynx 中浏览器 [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) 的限制，需要使用 [Memory Routing](https://tanstack.com/router/latest/docs/framework/react/guide/history-types#memory-routing)。

```tsx title=App.tsx
import {
  createMemoryHistory,
  createRouter,
  RouterProvider,
} from '@tanstack/react-router';

import { routeTree } from './routeTree.gen.js';

const memoryHistory = createMemoryHistory({
  initialEntries: ['/'],
});

const router = createRouter({
  routeTree,
  history: memoryHistory,
  isServer: false, // [!code highlight]
});

export function App() {
  return <RouterProvider router={router} />;
}
```

### Polyfill

为了确保 [URLSearchParams API](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) 在 Lynx 环境中正常工作，请在入口文件顶部添加 `url-search-params-polyfill`：

```tsx title=index.tsx
import 'url-search-params-polyfill';

import { root } from '@lynx-js/react';
import { App } from './App.jsx';

root.render(<App />);
```

### File-Based

TanStack Router 支持基于文件结构定义路由。将路由组件放置在 `src/routes` 目录中，其中 `__root.tsx` 作为根组件。

```jsx title="src/routes/__root.tsx"
import { createRootRoute, Outlet } from '@tanstack/react-router';

export const Route = createRootRoute({
  component: () => (
    <view>
      <Outlet />
    </view>
  ),
});
```

```jsx title="src/routes/index.tsx"
import { createFileRoute } from '@tanstack/react-router';

export const Route = createFileRoute('/')({
  component: () => <view>首页</view>,
});
```

`@tanstack/router-plugin/rspack` 会自动扫描 `src/routes` 目录并生成包含所有路由定义和类型信息的 `routeTree.gen.ts` 文件。该生成文件包括：

- 路由配置
- 路由的 TypeScript 接口
- 完整的路由树结构

### 示例


**下面是一个示例: tanstack-router**

**Entry:** `src/tanstack-router`
**Bundle:** `dist/main.lynx.bundle` | Web: `dist/main.web.bundle`

```tsx
import { createMemoryHistory, createRouter, RouterProvider } from "@tanstack/react-router";

import { routeTree } from "./routeTree.gen.js";

const memoryHistory = createMemoryHistory({
  initialEntries: ["/"],
});

const router = createRouter({
  routeTree,
  history: memoryHistory,
  isServer: false,
  origin: "http://localhost",
});

export function App() {
  return <RouterProvider router={router} />;
}

```


