后端-Day 01 - 项目初始化与环境搭建

0 阅读2分钟

Day 01 - 项目初始化与环境搭建

日期: 第1天
目标: 搭建 Node.js + TypeScript + Express + MongoDB 后端项目基础架构

📋 任务清单

  • 初始化 Node.js 项目并配置 TypeScript
  • 安装核心依赖(Express、MongoDB、Solana)
  • 配置项目目录结构
  • 设置开发和生产环境配置
  • 配置 ESLint 和 Prettier

💻 核心代码

1. 初始化项目

mkdir geng-backend && cd geng-backend
npm init -y
npm install typescript @types/node ts-node tsx --save-dev
npx tsc --init

2. 安装核心依赖

# 框架和工具
npm install express cors body-parser dotenv
npm install @types/express @types/cors --save-dev

# 数据库
npm install mongoose
npm install @types/mongoose --save-dev

# Solana 相关
npm install @solana/web3.js @coral-xyz/anchor @raydium-io/raydium-sdk
npm install @metaplex-foundation/js @metaplex-foundation/umi

# 认证和安全
npm install jsonwebtoken joi bs58 tweetnacl
npm install @types/jsonwebtoken --save-dev

# 实时通信
npm install socket.io

# 日志和定时任务
npm install winston node-cron node-schedule

# 缓存
npm install node-cache

# 工具
npm install axios

3. TypeScript 配置 (tsconfig.json)

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "moduleResolution": "node",
    "types": ["node"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

4. 项目目录结构

geng-backend/
├── src/
│   ├── @types/           # TypeScript 类型定义
│   ├── controller/       # 业务逻辑控制器
│   ├── db/               # 数据库连接配置
│   ├── jobs/             # 定时任务
│   ├── middleware/       # 中间件
│   ├── models/           # Mongoose 模型
│   ├── program/          # Solana 程序交互
│   ├── routes/           # API 路由
│   ├── service/          # 服务层
│   ├── sockets/          # WebSocket 处理
│   ├── utils/            # 工具函数
│   └── index.ts          # 入口文件
├── .env                  # 环境变量
├── tsconfig.json         # TypeScript 配置
└── package.json          # 项目依赖

5. 基础 Express 服务器 (src/index.ts)

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import 'dotenv/config';

const app = express();
const port = process.env.PORT || 5000;

const corsOptions = {
  origin: '*',
  credentials: false,
};

app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {
  res.json({ 
    status: 'ok',
    message: 'Geng Backend API'
  });
});

app.listen(port, () => {
  console.log(`🚀 Server running on port ${port}`);
});

⚠️ 常见问题

问题1:TypeScript 编译错误

现象: Cannot find module 'express'

解决方案: 安装类型定义包

npm install @types/express @types/node @types/cors --save-dev

问题2:环境变量未生效

现象: process.env.PORT 为 undefined

解决方案: 确保导入 dotenv

import 'dotenv/config';  // 在文件顶部

📝 总结

✅ 完成后端项目基础搭建


时间估计: 2-3 小时 | 难度: ⭐ 简单 | 关键词: Node.js、TypeScript、Express