Published on

搭建fastify后端 | fastify 脚手架项目

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

1. 创建

  1. 安装包

    mkdir fastifyScaffold
    cd fastifyScaffold
    
    pnpm init
    # fastify
    pnpm add fastify fastify-cli
    # 支持trpc服务
    pnpm add zod @trpc/server
    
    # typescript TypeScript编译器, 负责把 .ts 编译成 .js
    # tsx 一种更快、更现代的 TS/JS 执行器 运行 .ts 文件,支持 ESM/顶层 await/自动重启,比 ts-node 快很多
    # ts-node 传统的 TS 执行器 也是运行 .ts 文件,但速度比 tsx 慢,兼容性好
    # @types/node Node.js 类型定义文件 让 TypeScript 知道 Node.js 的 API 类型,比如 fs, path
    pnpm add -D typescript tsx ts-node @types/node
    
  2. tsconfig npx tsc --init

    // 
    // ./tsconfig.json
    {
      "compilerOptions": {
        "target": "ES2020",
        "lib": ["ES2020"],
        "module": "esnext",
        "moduleResolution": "Node",
        "outDir": "dist",
        "rootDir": "src",
        "strict": true,
        "esModuleInterop": true,
        "resolveJsonModule": true,
        "skipLibCheck": true,
        "types": ["node"]
      },
      "include": ["src"],
      "exclude": ["node_modules", "dist"]
    }
    
  3. 启动脚本在 package.json

    "scripts": {
      "build": "tsc",
      "start": "fastify start dist/src/index.js",
      "dev": "tsx src/index.ts",
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    
  4. 要想在index.ts中使用await, 需要修改2个地方

    1. package.json: "type": "module",
    2. tsconfig.json: "module": "esnext",