0. 基础环境配置有两种【typescript,编译,代码格式】

0.1 第一种方式

使用了nodemon, eslint, prettier, sucrase, typescript

(0.1.1) 新建nodemon.json 【使用的是sucrase-node编译】

  1. {
  2. "watch": ["src"],
  3. "ext": "ts",
  4. "execMap": {
  5. "ts": "sucrase-node src/server.ts"
  6. }
  7. }

**

(0.1.2) yarn eslint —init

.eslintrc.js

  1. module.exports = {
  2. env: {
  3. browser: true,
  4. es6: true,
  5. },
  6. extends: [
  7. 'plugin:@typescript-eslint/recommended',
  8. 'prettier/@typescript-eslint',
  9. 'standard',
  10. ],
  11. globals: {
  12. Atomics: 'readonly',
  13. SharedArrayBuffer: 'readonly',
  14. },
  15. parser: '@typescript-eslint/parser',
  16. parserOptions: {
  17. ecmaVersion: 2018,
  18. sourceType: 'module',
  19. },
  20. plugins: ['@typescript-eslint'],
  21. rules: {},
  22. };

(0.1.3) package.json

  1. {
  2. "name": "ts-express-boilerplate",
  3. "version": "1.0.0",
  4. "main": "index.js",
  5. "license": "MIT",
  6. "scripts": {
  7. "start:dev": "nodemon src/server.ts",
  8. "build": "sucrase ./src -d ./dist --transforms typescript,imports"
  9. },
  10. "devDependencies": {
  11. "@types/cors": "^2.8.6",
  12. "@types/express": "^4.17.6",
  13. "@types/mongoose": "^5.7.14",
  14. "@typescript-eslint/eslint-plugin": "^2.30.0",
  15. "@typescript-eslint/parser": "^2.30.0",
  16. "eslint": "^6.8.0",
  17. "eslint-config-prettier": "^6.11.0",
  18. "eslint-config-standard": "^14.1.1",
  19. "eslint-plugin-import": "^2.20.2",
  20. "eslint-plugin-node": "^11.1.0",
  21. "eslint-plugin-prettier": "^3.1.3",
  22. "eslint-plugin-promise": "^4.2.1",
  23. "eslint-plugin-standard": "^4.0.1",
  24. "nodemon": "^2.0.3",
  25. "prettier": "^2.0.5",
  26. "sucrase": "^3.13.0",
  27. "typescript": "^3.8.3"
  28. },
  29. "dependencies": {
  30. "cors": "^2.8.5",
  31. "express": "^4.17.1",
  32. "mongoose": "^5.9.11"
  33. }
  34. }

**


0.2 第二种方式

nodemon, typeorm, typescript(tsc —init)

(0.2.1) nodemon.json 【使用ts-node编译】

  1. {
  2. "watch": ["./src/**/*", ".env"],
  3. "ext": "ts",
  4. "exec": "ts-node ./src/index.ts"
  5. }

(0.2.2) ormconfig.json

  1. {
  2. "type": "postgres",
  3. "host": "localhost",
  4. "port": 5432,
  5. "username": "postgres",
  6. "password": "postgres",
  7. "database": "groceries",
  8. "synchronize": true,
  9. "logging": true,
  10. "entities": ["src/entities/**/*.ts", "dist/entities/**/*.js"]
  11. }

(0.2.3) tsconfig.json 【tsc —init生成的文件】

参考连接: https://github.com/ChenxiiCheng/Express-TypeScript-MVC/blob/master/tsconfig.json

(0.2.4) package.json

  1. {
  2. "name": "ts-groceries",
  3. "version": "1.0.0",
  4. "main": "index.ts",
  5. "author": "Chenxi <chenxic1011@gmail.com>",
  6. "license": "MIT",
  7. "scripts": {
  8. "start": "node ./dist/index.js",
  9. "start:dev": "nodemon"
  10. },
  11. "devDependencies": {
  12. "@types/body-parser": "^1.19.0",
  13. "@types/express": "^4.17.6",
  14. "@types/node": "^13.13.4",
  15. "nodemon": "^2.0.3",
  16. "ts-node": "^8.9.1",
  17. "typescript": "^3.8.3"
  18. },
  19. "dependencies": {
  20. "body-parser": "^1.19.0",
  21. "dotenv": "^8.2.0",
  22. "express": "^4.17.1",
  23. "pg": "^8.0.3",
  24. "reflect-metadata": "^0.1.13",
  25. "typeorm": "^0.2.24"
  26. }
  27. }

**



src**

  • controllers 目录
  • route.ts
  • schemas / entities 目录**【使用mongodb的话是shcemas,使用typeOrm的话是entities目录】**
  • app.ts
  • server.ts

1. app.ts【express实例,配置middleware, route, controller】

  1. import express from 'express';
  2. import cors from 'cors';
  3. import mongoose from 'mongoose';
  4. import routes from './route';
  5. class App {
  6. public express: express.Application;
  7. constructor() {
  8. this.express = express();
  9. this.middlewares();
  10. this.database();
  11. this.routes();
  12. }
  13. private middlewares(): void {
  14. this.express.use(express.json());
  15. this.express.use(cors());
  16. }
  17. private database(): void {
  18. mongoose.connect(
  19. 'mongodb+srv://brad123:brad123@contactkeeper-j0cwi.mongodb.net/tsexpress?retryWrites=true&w=majority',
  20. {
  21. useNewUrlParser: true,
  22. useUnifiedTopology: true,
  23. }
  24. );
  25. }
  26. private routes(): void {
  27. this.express.use(routes);
  28. }
  29. }
  30. export default new App().express;

2. server.ts 【总的地方】

  1. import app from './app';
  2. app.listen(3333);

3. route.ts【路由文件】

  1. import { Router } from 'express';
  2. import UserController from './controllers/UserController';
  3. const routes = Router();
  4. routes.get('/users', UserController.index);
  5. routes.post('/users', UserController.create);
  6. export default routes;

4. 模型

第一种 使用mongodb:shcemas/User.ts

  1. import { Schema, model, Document } from 'mongoose';
  2. interface IUser extends Document {
  3. email?: string;
  4. firstName?: string;
  5. lastName?: string;
  6. fullName: () => string;
  7. }
  8. const UserSchema = new Schema(
  9. {
  10. email: String,
  11. firstName: String,
  12. lastName: String,
  13. },
  14. {
  15. timestamps: true,
  16. }
  17. );
  18. UserSchema.methods.fullName = function (): string {
  19. return this.firstName + ' ' + this.lastName;
  20. };
  21. export default model<IUser>('User', UserSchema);

第二种 使用typeOrm:entities/Item.ts

  1. import {
  2. Entity,
  3. BaseEntity,
  4. PrimaryGeneratedColumn,
  5. Column,
  6. CreateDateColumn,
  7. ManyToOne,
  8. } from 'typeorm';
  9. import { GroceryList } from './GroceryList';
  10. @Entity('items')
  11. export class Item extends BaseEntity {
  12. @PrimaryGeneratedColumn('uuid')
  13. id: string;
  14. @Column({
  15. type: 'text',
  16. })
  17. name: string;
  18. @CreateDateColumn({
  19. type: 'timestamp',
  20. })
  21. created: string;
  22. @ManyToOne((type) => GroceryList, (groceryList) => groceryList.items)
  23. grocery_list: GroceryList;
  24. }

5. controllers/UserController.ts

  1. import { Request, Response } from 'express';
  2. import User from '../schemas/User';
  3. class UserController {
  4. public async index(req: Request, res: Response): Promise<Response> {
  5. const users = await User.find();
  6. return res.json(users);
  7. }
  8. public async create(req: Request, res: Response): Promise<Response> {
  9. const user = await User.create(req.body);
  10. // user.fullName()
  11. return res.json(user);
  12. }
  13. }
  14. export default new UserController();