设置 tRPC 客户端
1. 安装 tRPC 客户端库
¥ Install the tRPC Client library
使用你喜欢的包管理器安装 @trpc/client
库,并安装包含一些所需类型的 @trpc/server
。
¥Use your preferred package manager to install the @trpc/client
library, and also install @trpc/server
which contains some required types.
- npm
- yarn
- pnpm
- bun
bash
npm install @trpc/client @trpc/server
bash
npm install @trpc/client @trpc/server
bash
yarn add @trpc/client @trpc/server
bash
yarn add @trpc/client @trpc/server
bash
pnpm add @trpc/client @trpc/server
bash
pnpm add @trpc/client @trpc/server
bash
bun add @trpc/client @trpc/server
bash
bun add @trpc/client @trpc/server
2. 导入你的应用路由
¥ Import your App Router
将 AppRouter
类型导入客户端应用。这种类型保存了整个 API 的形状。
¥Import your AppRouter
type into the client application. This type holds the shape of your entire API.
ts
import type {AppRouter } from '../server/router';
ts
import type {AppRouter } from '../server/router';
通过使用 import type
,你可以确保在编译时删除引用,这意味着你不会无意中将服务器端代码导入到客户端中。欲了解更多信息,请参阅 Typescript 文档。
¥By using import type
you ensure that the reference will be stripped at compile-time, meaning you don't inadvertently import server-side code into your client. For more information, see the Typescript docs.
3. 初始化 tRPC 客户端
¥ Initialize the tRPC client
使用 createTRPCProxyClient
方法创建 tRPC 客户端,并添加 links
数组,其中 终止链接 指向你的 API。要了解有关 tRPC 链接的更多信息,点击这里。
¥Create a tRPC client with the createTRPCProxyClient
method, and add a links
array with a terminating link pointing at your API. To learn more about tRPC links, click here.
client.tsts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasync headers() {return {authorization: getAuthCookie(),};},}),],});
client.tsts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasync headers() {return {authorization: getAuthCookie(),};},}),],});
4. 使用 tRPC 客户端
¥ Use the tRPC Client
在底层,这会创建一个类型化的 JavaScript 代理,它允许你以完全类型安全的方式与 tRPC API 进行交互:
¥Under the hood this creates a typed JavaScript Proxy which allows you to interact with your tRPC API in a fully type-safe way:
client.tsts
const bilbo = await client.getUser.query('id_bilbo');// => { id: 'id_bilbo', name: 'Bilbo' };const frodo = await client.createUser.mutate({ name: 'Frodo' });// => { id: 'id_frodo', name: 'Frodo' };
client.tsts
const bilbo = await client.getUser.query('id_bilbo');// => { id: 'id_bilbo', name: 'Bilbo' };const frodo = await client.createUser.mutate({ name: 'Frodo' });// => { id: 'id_frodo', name: 'Frodo' };
你都准备好了!
¥You're all set!