0. 基础环境配置有两种【typescript,编译,代码格式】
0.1 第一种方式
使用了nodemon, eslint, prettier, sucrase, typescript
(0.1.1) 新建nodemon.json 【使用的是sucrase-node编译】
{"watch": ["src"],"ext": "ts","execMap": {"ts": "sucrase-node src/server.ts"}}
(0.1.2) yarn eslint —init
.eslintrc.js
module.exports = {env: {browser: true,es6: true,},extends: ['plugin:@typescript-eslint/recommended','prettier/@typescript-eslint','standard',],globals: {Atomics: 'readonly',SharedArrayBuffer: 'readonly',},parser: '@typescript-eslint/parser',parserOptions: {ecmaVersion: 2018,sourceType: 'module',},plugins: ['@typescript-eslint'],rules: {},};
(0.1.3) package.json
{"name": "ts-express-boilerplate","version": "1.0.0","main": "index.js","license": "MIT","scripts": {"start:dev": "nodemon src/server.ts","build": "sucrase ./src -d ./dist --transforms typescript,imports"},"devDependencies": {"@types/cors": "^2.8.6","@types/express": "^4.17.6","@types/mongoose": "^5.7.14","@typescript-eslint/eslint-plugin": "^2.30.0","@typescript-eslint/parser": "^2.30.0","eslint": "^6.8.0","eslint-config-prettier": "^6.11.0","eslint-config-standard": "^14.1.1","eslint-plugin-import": "^2.20.2","eslint-plugin-node": "^11.1.0","eslint-plugin-prettier": "^3.1.3","eslint-plugin-promise": "^4.2.1","eslint-plugin-standard": "^4.0.1","nodemon": "^2.0.3","prettier": "^2.0.5","sucrase": "^3.13.0","typescript": "^3.8.3"},"dependencies": {"cors": "^2.8.5","express": "^4.17.1","mongoose": "^5.9.11"}}
**
0.2 第二种方式
nodemon, typeorm, typescript(tsc —init)
(0.2.1) nodemon.json 【使用ts-node编译】
{"watch": ["./src/**/*", ".env"],"ext": "ts","exec": "ts-node ./src/index.ts"}
(0.2.2) ormconfig.json
{"type": "postgres","host": "localhost","port": 5432,"username": "postgres","password": "postgres","database": "groceries","synchronize": true,"logging": true,"entities": ["src/entities/**/*.ts", "dist/entities/**/*.js"]}
(0.2.3) tsconfig.json 【tsc —init生成的文件】
参考连接: https://github.com/ChenxiiCheng/Express-TypeScript-MVC/blob/master/tsconfig.json
(0.2.4) package.json
{"name": "ts-groceries","version": "1.0.0","main": "index.ts","author": "Chenxi <chenxic1011@gmail.com>","license": "MIT","scripts": {"start": "node ./dist/index.js","start:dev": "nodemon"},"devDependencies": {"@types/body-parser": "^1.19.0","@types/express": "^4.17.6","@types/node": "^13.13.4","nodemon": "^2.0.3","ts-node": "^8.9.1","typescript": "^3.8.3"},"dependencies": {"body-parser": "^1.19.0","dotenv": "^8.2.0","express": "^4.17.1","pg": "^8.0.3","reflect-metadata": "^0.1.13","typeorm": "^0.2.24"}}
**
src**
- controllers 目录
- route.ts
- schemas / entities 目录**【使用mongodb的话是shcemas,使用typeOrm的话是entities目录】**
- app.ts
- server.ts
1. app.ts【express实例,配置middleware, route, controller】
import express from 'express';import cors from 'cors';import mongoose from 'mongoose';import routes from './route';class App {public express: express.Application;constructor() {this.express = express();this.middlewares();this.database();this.routes();}private middlewares(): void {this.express.use(express.json());this.express.use(cors());}private database(): void {mongoose.connect('mongodb+srv://brad123:brad123@contactkeeper-j0cwi.mongodb.net/tsexpress?retryWrites=true&w=majority',{useNewUrlParser: true,useUnifiedTopology: true,});}private routes(): void {this.express.use(routes);}}export default new App().express;
2. server.ts 【总的地方】
import app from './app';app.listen(3333);
3. route.ts【路由文件】
import { Router } from 'express';import UserController from './controllers/UserController';const routes = Router();routes.get('/users', UserController.index);routes.post('/users', UserController.create);export default routes;
4. 模型
第一种 使用mongodb:shcemas/User.ts
import { Schema, model, Document } from 'mongoose';interface IUser extends Document {email?: string;firstName?: string;lastName?: string;fullName: () => string;}const UserSchema = new Schema({email: String,firstName: String,lastName: String,},{timestamps: true,});UserSchema.methods.fullName = function (): string {return this.firstName + ' ' + this.lastName;};export default model<IUser>('User', UserSchema);
第二种 使用typeOrm:entities/Item.ts
import {Entity,BaseEntity,PrimaryGeneratedColumn,Column,CreateDateColumn,ManyToOne,} from 'typeorm';import { GroceryList } from './GroceryList';@Entity('items')export class Item extends BaseEntity {@PrimaryGeneratedColumn('uuid')id: string;@Column({type: 'text',})name: string;@CreateDateColumn({type: 'timestamp',})created: string;@ManyToOne((type) => GroceryList, (groceryList) => groceryList.items)grocery_list: GroceryList;}
5. controllers/UserController.ts
import { Request, Response } from 'express';import User from '../schemas/User';class UserController {public async index(req: Request, res: Response): Promise<Response> {const users = await User.find();return res.json(users);}public async create(req: Request, res: Response): Promise<Response> {const user = await User.create(req.body);// user.fullName()return res.json(user);}}export default new UserController();
