前言: 最近在做一个小项目,因为工作量也不是很大就想着试试使用typescript开发,项目环境已经搭建完成,顺便做个文档记录一下。
依赖安装
tyarn add typescript ts-node koa koa-router nodemon @types/koa @types/node @types/koa-router -D
typescript 配置编译文件
生成tsc编译文件: tsc --init ; (我全局安装了typescript所以直接使用tsc命令,局部安装可以换成: npx tsc --init)
koa 启动文件app.ts
import * as Koa from 'koa';
import * as Router from 'koa-router';
import inderRouter from './router/index';
const app = new Koa();
const router = new Router();
app.use(inderRouter.routes());
router.get('/', async (ctx: any) => {
ctx.body = 'Hello!';
});
app.use(router.routes());
app.listen(9000);
package.json 脚本
"scripts": {
"start": "nodemon --exec ts-node ./server/app.ts",
"server": "tsc ./server/app.ts",
},
运行npm start 启动程序
问题记录
- [ts] 其类型缺少调用或构造签名的表达式无法使用 "new" 错误:
TSError: ⨯ Unable to compile TypeScript:
server/app.ts:6:17 - error TS2351: This expression is not constructable.
Type 'typeof Application' has no construct signatures.
const app = new Koa();
解决: tsconfig.json 文件里去掉 "esModuleInterop": true