Tkoa 是使用 typescript 编写的 koa 框架!
尽管它是基于 typescript 编写,但是你依然还是可以使用一些 node.js 框架和基于 koa 的中间件。
不仅如此,你还可以享受 typescript 的类型检查系统和方便地使用 typescript 进行测试!
TKoa 需要>= typescript v3.1.0和node v7.6.0版本。
$ npm install tkoa
import tKoa = require('tkoa'); interface ctx { res: { end: Function } } const app = new tKoa(); // response app.use((ctx: ctx) => { ctx.res.end('Hello T-koa!'); }); app.listen(3000);
Tkoa 是一个中间件框架,拥有两种中间件:
下面是一个日志记录中间件示例,其中使用了不同的中间件类型:
interface ctx { method: string, url: string } app.use(async (ctx: ctx, next: Function) => { const start = Date.now(); await next(); const ms = Date.now() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); });
// Middleware normally takes two parameters (ctx, next), ctx is the context for one request, // next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion. interface ctx { method: string, url: string } app.use((ctx: ctx, next: Function) => { const start = Date.now(); return next().then(() => { const ms = Date.now() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); }); });
![]() | 1 siloong 2019-04-17 15:49:38 +08:00 支持。btw,为什么不叫 Toa。。。 |
![]() | 2 solome 2019-04-17 16:19:00 +08:00 不理解这样做的意义(分割),不是已经存在`@types/koa`了么。 |
![]() | 3 askfermi 2019-04-17 16:20:53 +08:00 同楼上问 |
![]() | 4 maichael 2019-04-17 16:21:58 +08:00 同问,跟原有的 Koa + types 有什么区别。 |
5 18510047382 OP |
6 18510047382 OP |
![]() | 7 Axurez 2019-04-17 17:29:57 +08:00 为啥还在用 `import tKoa = require('tkoa');` 这种写法 |
8 18510047382 OP @Axurez 文档说明里已经写明了,这样用 commonjs 模块规范是为了更好地兼容 koa 中间件和 node.js 框架。 |
9 meteor957 2019-04-17 23:46:06 +08:00 via Android 赞。不过现在有 nestjs 了,用 ts 封装了 express.不知道 i 和楼主这个区别大不大 |
10 18510047382 OP @meteor957 其实就是 koa 和 Express 的差别 |
![]() | 11 Gea 2019-04-18 10:22:35 +08:00 typescript 版本的 koa 有什么优势吗,nest 我记得好像还有些注解的语法糖,用起来和 ng、sprintboot 很像 |
12 18510047382 OP @Gea 拥有 TypeScript 完整的类型检查系统,可以很方便的调试 |
13 18510047382 OP @siloong 都一样咯 |
![]() | 14 blanu 2019-05-08 04:29:43 +08:00 内部用 TS 实现和外部暴露 API 用 TS 写 Definition 差不多吧…… |
![]() | 15 blanu 2019-05-08 12:30:54 +08:00 今天又看了下,类型推断竟然是要你自己写 interface,要你这个有何用? 还有什么用 legacy 的 import 语法说是为了兼容 commonjs,我佛了,tsconfig 里面不会自己设置? 这就是个骗项目 |
![]() | 16 cl903254852 2019-05-22 14:47:44 +08:00 不是有 @types/koa 吗? 而且 import tKoa = require('tkoa'); 是什么写法。。。 没明白 |