原文地址:使用typescript改造koa开发框架

强类型的 TypeScript 开发体验和维护项目上相比 JavaScript 有着明显的优势,那么对常用的脚手架进行改造也就势在必行了。

接下来开始对基于 koa 框架的 node 后端脚手架进行改造:

  1. 项目开发环境 和 typescript 编译环境的搭建;
  2. nodekoa、koa中间件和使用到的库 添加类型化支持;
  3. 基于 typesript 的特性改造项目。

项目开发环境搭建

基于 gulp 搭建开发编译环境,gulp-typescript 插件用于编译 typescript 文件, gulp-nodemon 则可以监控文件内容的变更,自动编译和重启node服务,提升开发效率。

npm install -D gulp gulp-nodemon gulp-typescript ts-node typescript

gulp 的配置

gulpfile.js 的设置

const { src, dest, watch, series, task } = require('gulp');
const del = require('del');
const ts = require('gulp-typescript');
const nodemon = require('gulp-nodemon');
const tsProject = ts.createProject('tsconfig.json'); function clean(cb) {
return del(['dist'], cb);
} // 输出 js 到 dist目录
function toJs() {
return src('src/**/*.ts')
.pipe(tsProject())
.pipe(dest('dist'));
} // nodemon 监控 ts 文件
function runNodemon() {
nodemon({
inspect: true,
script: 'src/app.ts',
watch: ['src'],
ext: 'ts',
env: { NODE_ENV: 'development' },
// tasks: ['build'],
}).on('crash', () => {
console.error('Application has crashed!\n');
});
} const build = series(clean, toJs);
task('build', build);
exports.build = build;
exports.default = runNodemon;

typescript 的配置

tsconfig.json 的设置

{
"compilerOptions": {
"baseUrl": ".", // import的相对起始路径
"outDir": "./dist", // 构建输出目录
"module": "commonjs",
"target": "esnext",// node 环境支持 esnext
"allowSyntheticDefaultImports": true,
"importHelpers": true,
"strict": false,
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"noImplicitReturns": true,
"experimentalDecorators": true, // 开启装饰器的使用
"emitDecoratorMetadata": true,
"allowJs": true,
"sourceMap": true,
"paths": {
"@/*": [ "src/*" ]
}
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}

eslint 的配置

当然 eslint 也要添加对 typescript 对支持

npm install -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

.eslintrc.json 的设置

{
"env": {
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"indent": [ "warn", 2 ],
"no-unused-vars": 0
}
}

package.json 运行配置

最后就是设置 package.json 的 scripts

  "scripts": {
"start": "gulp",// dev
"build": "gulp build", // output
"eslint": "eslint --fix --ext .js,.ts src/",
"server": "export NODE_ENV=production && node dist/app" // production server
},

添加类型化支持

项目主要使用到了以下的组件

  • jsonwebtoken
  • koa
  • koa-body
  • koa-compress
  • koa-favicon
  • koa-logger
  • koa-router
  • koa-static
  • koa2-cors
  • log4js

那么就要安装对应的 type 文件,当然别忘了 @types/node

npm install -D @types/jsonwebtoken @types/koa @types/koa-compress @types/koa-favicon @types/koa-logger @types/koa-router @types/koa-static @types/koa2-cors @types/log4js @types/node

使用 typescript 装饰器 改造项目

.net mvc 框架有个很便利的地方就是 使用装饰器对控制器进行配置,现在通过 typescript 的装饰器也可以实现相同的功能。这里需要使用到反射相关的库 reflect-metadata,用过 JavaC# 的小伙伴,对反射的原理一定不陌生。

定义http请求的装饰器

我们再也不需要在路由配置和控制器方法之间来回查找和匹配了

import 'reflect-metadata'
import { ROUTER_MAP } from '../constant' /**
* @desc 生成 http method 装饰器
* @param {string} method - http method,如 get、post、head
* @return Decorator - 装饰器
*/
function createMethodDecorator(method: string) {
// 装饰器接收路由 path 作为参数
return function httpMethodDecorator(path: string) {
return (proto: any, name: string) => {
const target = proto.constructor;
const routeMap = Reflect.getMetadata(ROUTER_MAP, target, 'method') || [];
routeMap.push({ name, method, path });
Reflect.defineMetadata(ROUTER_MAP, routeMap, target, 'method');
};
};
} // 导出 http method 装饰器
export const post = createMethodDecorator('post'); export const get = createMethodDecorator('get'); export const del = createMethodDecorator('del'); export const put = createMethodDecorator('put'); export const patch = createMethodDecorator('patch'); export const options = createMethodDecorator('options'); export const head = createMethodDecorator('head'); export const all = createMethodDecorator('all');

装饰控制器的方法

export default class Sign {

  @post('/login')
async login (ctx: Context) {
const { email, password } = ctx.request.body;
const users = await userDao.getUser({ email });
// ...
return ctx.body = {
code: 0,
message: '登录成功',
data
};
} @post('/register')
async register (ctx: Context) {
const { email, password } = ctx.request.body;
const salt = makeSalt();
// ...
return ctx.body = {
code: 0,
message: '注册成功!',
data
}
} }

收集元数据和添加路由

我们已经把装饰器添加到对应控制器的方法上了,那么怎么把元数据收集起来呢?这就需要用到 node 提供的 fs 文件模块,node服务第一次启动的时候,扫描一遍controller文件夹,收集到所有控制器模块,结合装饰器收集到的metadata,就可以把对应的方法添加到 koa-router

import 'reflect-metadata'
import fs from 'fs'
import path from 'path'
import { ROUTER_MAP } from './constant'
import { RouteMeta } from './type'
import Router from 'koa-router' const addRouter = (router: Router) => {
const ctrPath = path.join(__dirname, 'controller');
const modules: ObjectConstructor[] = [];
// 扫描controller文件夹,收集所有controller
fs.readdirSync(ctrPath).forEach(name => {
if (/^[^.]+?\.(t|j)s$/.test(name)) {
modules.push(require(path.join(ctrPath, name)).default)
}
});
// 结合meta数据添加路由
modules.forEach(m => {
const routerMap: RouteMeta[] = Reflect.getMetadata(ROUTER_MAP, m, 'method') || [];
if (routerMap.length) {
const ctr = new m();
routerMap.forEach(route => {
const { name, method, path } = route;
router[method](path, ctr[name]);
})
}
})
} export default addRouter

最后

这样对koa项目脚手架的改造基本完成,源码请查看 koa-server

使用typescript改造koa开发框架的更多相关文章

  1. 使用 TypeScript 改造构建工具及测试用例

    最近的一段时间一直在搞TypeScript,一个巨硬出品.赋予JavaScript语言静态类型和编译的语言. 第一个完全使用TypeScript重构的纯Node.js项目已经上线并稳定运行了. 第二个 ...

  2. Winform开发框架之插件化应用框架实现

    支持插件化应用的开发框架能给程序带来无穷的生命力,也是目前很多系统.程序追求的重要方向之一,插件化的模块,在遵循一定的接口标准的基础上,可以实现快速集成,也就是所谓的热插拔操作,可以无限对已经开发好系 ...

  3. iKcamp新书上市《Koa与Node.js开发实战》

    内容摘要 Node.js 10已经进入LTS时代!其应用场景已经从脚手架.辅助前端开发(如SSR.PWA等)扩展到API中间层.代理层及专业的后端开发.Node.js在企业Web开发领域也日渐成熟,无 ...

  4. Javascript装饰器的妙用

    最近新开了一个Node项目,采用TypeScript来开发,在数据库及路由管理方面用了不少的装饰器,发觉这的确是一个好东西.装饰器是一个还处于草案中的特性,目前木有直接支持该语法的环境,但是可以通过 ...

  5. 解密国内BAT等大厂前端技术体系-腾讯篇(长文建议收藏)

    1 引言 为了了解当前前端的发展趋势,让我们从国内各大互联网大厂开始,了解他们的最新动态和未来规划.这是解密大厂前端技术体系的第三篇,前两篇已经讲述了阿里和百度在前端技术这几年的技术发展.这一篇从腾讯 ...

  6. Node.js躬行记(9)——微前端实践

    后台管理系统使用的是umi框架,随着公司业务的发展,目前已经变成了一个巨石应用,越来越难维护,有必要对其进行拆分了. 计划是从市面上挑选一个成熟的微前端框架,首先选择的是 icestark,虽然文档中 ...

  7. KoaHub.js是基于 Koa.js 平台的 Node.js web 快速开发框架

    koahubjs KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架.可以直接在项目里使用 ES6/7(Generator Function, Class, A ...

  8. 基于 Koa.js 平台的 Node.js web 快速开发框架KoaHub.js demo 可安装

    KoaHub.js demo KoaHub.js KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架.可以直接在项目里使用 ES6/7(Generator Fu ...

  9. KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架之koahub-yilianyun

    koahub-yilianyun 微信易联云打印机接口 koahub-yilianyun易联云打印机node接口 Installation $ npm install koahub-yilianyun ...

随机推荐

  1. 神奇的 SQL 之 联表细节 → MySQL JOIN 的执行过程(二)

    开心一刻 一头母牛在吃草,突然一头公牛从远处狂奔而来说:“快跑啊!!楼主来了!” 母牛说:“楼主来了关我屁事啊?” 公牛急忙说:“楼主吹牛逼呀!” 母牛大惊,拔腿就跑,边跑边问:“你是公牛你怕什么啊? ...

  2. 高校表白app用后感

    此款app前提是我们自行设计研发的app,其次满足了在校大学生对谈恋爱的需求,可以说是一款简单实用,好操作的软件.下面我根据自己的使用体验简单的介绍一下此软件: (1)首先对于未使用过的用户,你需要在 ...

  3. 「Vijos 1284」「OIBH杯NOIP2006第二次模拟赛」佳佳的魔法阵

    佳佳的魔法阵 背景 也许是为了捕捉猎物(捕捉MM?),也许是因为其它原因,总之,佳佳准备设计一个魔法阵.而设计魔法阵涉及到的最关键问题,似乎就是那些带有魔力的宝石的摆放-- 描述 魔法阵是一个\(n ...

  4. 12款好用的Visual Studio插件,最后一款良心推荐

    目录 01 CodeMaid 02 Markdown Editor 03 ReSharper 04 GitHub Extension for Visual Studio 05 ZenCoding 06 ...

  5. SpringBoot-2.1.1系列二:使用websocket

    1.什么是websocket? WebSocket协议是基于TCP的一种新的网络协议.它实现了浏览器与服务器全双工(full-duplex)通信--允许服务器主动发送信息给客户端. 2.为什么需要使用 ...

  6. zookeeper作配置中心(存储支付信息)

    zookeeper作配置中心(存储敏感信息) 前提:最近在项目中需要用到支付接口,支付宝或者微信支付,根据官方文档,需要配置一些诸如notify-url或者app-private-key等信息,这些信 ...

  7. ACM北大暑期课培训第二天

    今天继续讲的动态规划 ... 补充几个要点: 1. 善于利用滚动数组(可减少内存,用法与计算方向有关) 2.升维 3.可利用一些数据结构等方法使代码更优  (比如优先队列) 4.一般看到数值小的 (十 ...

  8. 【Java基础总结】GUI

    GUI(Graphical User Interface),图形用户接口 CLI(Command Line User Interface),命令行用户接口 1. 容器 Container GUI主要位 ...

  9. Spring(一)开篇

    目录 1.Spring 介绍 2.Spring 框架的演变 3.Spring 整体架构 Core Container Data Access/Integration Web AOP Test 最后 1 ...

  10. python字典的遍历

    遍历字典: keys()  .values() .items() 1. xxx.keys()    :    返回字典的所有的key     返回一个序列,序列中保存有字典的所有的键 效果图: 代码: ...