You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js项目中TRPC的appRouter类型如何导出给Vite.js项目使用

跨项目共享TRPC appRouter类型解决方案

1. 确保Next.js项目正确导出路由类型

在你的Next.js TRPC路由文件中,必须显式导出AppRouter类型,这是跨项目共享类型的核心:

// nextjs-project/src/server/trpc/router/index.ts
import { initTRPC } from '@trpc/server';
import { z } from 'zod';

const t = initTRPC.create();

export const appRouter = t.router({
  hello: t.procedure
    .input(z.object({ name: z.string() }))
    .query(({ input }) => ({ greeting: `Hello ${input.name}` })),
  // 其他路由定义...
});

// 单独导出路由类型,这一步不可省略
export type AppRouter = typeof appRouter;

2. 配置Vite项目的TypeScript路径映射

修改Vite项目的tsconfig.json,添加对Next.js项目的类型引用配置,让TypeScript能识别跨项目的类型文件:

// vite-project/tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@trpc-shared/*": ["../nextjs-project/src/server/trpc/*"] // 根据你的实际项目路径调整
    },
    "declaration": true,
    "declarationMap": true
  },
  "include": ["src", "../nextjs-project/src/server/trpc"],
  "exclude": ["node_modules"]
}

3. 在Vite项目中正确初始化TRPC客户端

使用type-only导入AppRouter类型,避免导入运行时代码导致类型丢失:

// vite-project/src/utils/trpc.ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
// 仅导入类型,不导入运行时实例
import type { AppRouter } from '@trpc-shared/router';

export const trpc = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url: 'http://localhost:3000/api/trpc', // 你的Next.js TRPC API地址
    }),
  ],
});

4. 排查常见问题

  • 确认Next.js项目的tsconfig.json中compilerOptions.declaration设为true,确保生成.d.ts类型声明文件
  • 若使用monorepo结构,检查根目录package.json的workspaces配置,保证TypeScript能识别工作区内的包
  • 禁止直接导入appRouter实例到Vite项目,仅导入AppRouter类型

内容的提问来源于stack exchange,提问作者Ruzmetov job

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:13:24