設定 tRPC 客戶端
1. 安裝 tRPC 客戶端程式庫
使用您偏好的套件管理員來安裝 @trpc/client
程式庫,並安裝包含一些必要類型的 @trpc/server
。
- npm
- yarn
- pnpm
- bun
npm install @trpc/server@next @trpc/client@next
yarn add @trpc/server@next @trpc/client@next
pnpm add @trpc/server@next @trpc/client@next
bun add @trpc/server@next @trpc/client@next
2. 匯入您的應用程式路由器
將您的 AppRouter
類型匯入客戶端應用程式。此類型包含您整個 API 的形狀。
ts
import type {AppRouter } from '../server/router';
ts
import type {AppRouter } from '../server/router';
提示
透過使用 import type
,您可以確保在編譯時移除參考,表示您不會無意間將伺服器端程式碼匯入您的客戶端。如需更多資訊,請參閱 Typescript 文件。
3. 初始化 tRPC 客戶端
使用 createTRPCClient
方法建立 tRPC 客戶端,並加入一個包含指向您的 API 的終結連結的 links
陣列。如需深入了解 tRPC 連結,請按一下這裡。
client.tsts
import { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';const client = createTRPCClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasync headers() {return {authorization: getAuthCookie(),};},}),],});
client.tsts
import { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';const client = createTRPCClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000/trpc',// You can pass any HTTP headers you wish hereasync headers() {return {authorization: getAuthCookie(),};},}),],});
4. 使用 tRPC 客戶端
在幕後,這會建立一個型別化的JavaScript Proxy,讓您能以完全型別安全的方式與您的 tRPC API 互動
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' };
您已完成所有設定!