tRPC-Nuxt 项目教程
1. 项目的目录结构及介绍
tRPC-Nuxt/
├── .nuxt/
├── assets/
├── components/
├── composables/
├── layouts/
├── middleware/
├── node_modules/
├── pages/
├── plugins/
├── public/
├── server/
│ ├── api/
│ ├── trpc/
│ │ ├── _app.ts
│ │ ├── router.ts
│ │ └── context.ts
├── static/
├── store/
├── .gitignore
├── .npmrc
├── nuxt.config.ts
├── package.json
├── tsconfig.json
└── README.md
目录结构介绍
- .nuxt/: Nuxt 生成的构建文件。
- assets/: 存放静态资源,如样式文件、图片等。
- components/: 存放 Vue 组件。
- composables/: 存放可复用的组合式函数。
- layouts/: 存放页面布局文件。
- middleware/: 存放中间件文件。
- node_modules/: 存放项目依赖的 npm 包。
- pages/: 存放页面组件。
- plugins/: 存放插件文件。
- public/: 存放公开的静态文件。
- server/: 存放服务器端代码。
- api/: 存放 API 路由。
- trpc/: 存放 tRPC 相关文件。
- _app.ts: tRPC 应用入口文件。
- router.ts: tRPC 路由定义。
- context.ts: tRPC 上下文定义。
- static/: 存放静态文件,如 favicon.ico。
- store/: 存放 Vuex 状态管理文件。
- .gitignore: Git 忽略文件配置。
- .npmrc: npm 配置文件。
- nuxt.config.ts: Nuxt 配置文件。
- package.json: 项目依赖和脚本配置。
- tsconfig.json: TypeScript 配置文件。
- README.md: 项目说明文档。
2. 项目的启动文件介绍
nuxt.config.ts
nuxt.config.ts
是 Nuxt 项目的配置文件,包含了项目的各种配置选项,如路由、插件、模块等。以下是一些关键配置:
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
// 全局设置
ssr: true,
target: 'server',
// 模块
buildModules: [
'@nuxt/typescript-build',
'@nuxtjs/composition-api/module'
],
// 插件
plugins: [
'~/plugins/trpc.client.ts'
],
// 服务器配置
serverMiddleware: [
{ path: '/api', handler: '~/server/api/index.ts' }
],
// 构建配置
build: {
transpile: ['trpc-nuxt']
}
})
server/trpc/_app.ts
server/trpc/_app.ts
是 tRPC 应用的入口文件,定义了 tRPC 应用实例和路由。
import { createNuxtApiHandler } from 'trpc-nuxt'
import { appRouter } from './router'
import { createContext } from './context'
export default createNuxtApiHandler({
router: appRouter,
createContext
})
3. 项目的配置文件介绍
package.json
package.json
文件定义了项目的依赖、脚本和其他元数据。以下是一些关键配置:
{
"name": "tRPC-Nuxt",
"version": "1.0.0",
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"dependencies": {
"nuxt": "^2.15.0",
"trpc-nuxt": "^1.0.0