koa+typescript+typeorm+ioredis+mysql搭建koa项目
创建koa项目目录
1.创建目录,mkdir koa-example
2.创建package.json,npm init -y
生成项目
1.下载koa相关依赖
1
| yarn add koa koa-router koa-helmet koa-jwt body-parser
|
1
| yarn add @types/koa @types/koa-router @types/koa-helmet -D
|
在目录下新建一个src目录,然后src目录创建app.ts文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import * as Koa from 'koa'
class Application { private app: any
constructor() { this.app = new Koa() this.init() }
private init() { ..... }
public start(port: string) { this.app.listen(port) console.log(`listening at: http://127.0.0.1:${port}`) }
}
export default new Application()
|
2.下载配置typescript
1
| yarn add @types/node typescript tslint -D
|
在根目录下新建tsconfig.json文件,配置一下内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| { "compilerOptions": { "lib": [ "es5", "es6" ], "target": "es5", "module": "commonjs", "moduleResolution": "node", "outDir": "./build", "typeRoots": [ "./node_modules/@types/", "./src/@types/" ], "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowJs": true, "resolveJsonModule": true, "sourceMap": true } }
|
在根目录下创建tslint.json文件
1 2 3 4 5 6 7 8 9
| { "defaultSeverity": "error", "extends": [ "tslint:recommended" ], "jsRules": {}, "rules": {}, "rulesDirectory": [] }
|
3.使用nodemon自动重启服务,官方文档
在项目根目录下新建一个nodemon.json文件
1 2 3 4 5 6 7 8 9 10
| { "watch": ["src", "conf"], "ext": "ts,js", "ignore": [ "src/**/*.spec.ts", "node_modules" ], "exec": "ts-node bin/service.ts", "delay": 300 }
|
在src目录下新建一个bin文件夹,在bin文件夹下面新建一个service.ts文件
1 2 3 4 5
| import App from '../src/app';
let PORT: string = process.env.PORT || '3000'
App.start(PORT)
|
修改package.json
1 2 3 4 5 6 7 8 9 10 11 12
| { "name": "koa-app", "version": "0.0.1", "description": "", "scripts": { + "start": "ts-node src/app.ts", + "dev": "nodemon --config nodemon.json", }, ..... "author": "De scherpe", "license": "ISC" }
|
4.使用typeorm操作mysql,官方文档
1
| yarn add typeorm mysql reflect-metadata
|
在src目录下新建entities目录,存放数据表对象,例如创建一个user.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import {Column, CreateDateColumn, Entity, PrimaryColumn, PrimaryGeneratedColumn, UpdateDateColumn} from 'typeorm';
@Entity({name: 'vc_user'}) class User {
@PrimaryGeneratedColumn('increment') user_id: number
@Column({type: 'varchar',length:255 ,comment: '密码'}) password: string
@Column({type: 'varchar', legnth:10 , comment: '用户名'}) user_name: string
@CreateDateColumn({comment: '添加时间'}) date_add: Date
@UpdateDateColumn({comment: '更新时间'}) date_upd: Date }
|
5.使用ioredis操作redis,官方文档
1
| yarn add @types/ioredis -D
|
在根目录下新建一个utils文件夹,在utils文件件里创建redis.ts文件
1 2 3 4 5 6 7 8 9 10 11 12
| import * as Redis from 'ioredis'; import {REDIS_CONFIG} from '../../config/system.config';
class RedisClient { private redis: Redis.Redis
constructor() { this.redis = new Redis(REDIS_CONFIG) } }
export default RedisClient
|
最后更新时间: