TypeScript 和 Koa 实践

一,TypeScript 基本操作

安装 TypeScript:

npm install -g typescript

编写 test.ts 文件

function greeter(person: string) {
    return "Hello, " + person;
}

let user = [0, 1, 2];

document.body.innerHTML = greeter(user);

编译 ts 文件生成 js 文件:

tsc test.ts

提示:

greeter.ts(7,26): error TS2345: Argument of type 'number[]' 
is not assignable to parameter of type 'string'.


二,TypeScript 模块导入

生成 tsconfig.json 配置文件:

tsc --init

在使用 TypeScript 调用 Koa 时,因为 Koa 是基于 cjs 的模块,所以使用 esm 不可以直接引用。在之前的 TypeScript 中通常的做法是使用:

import * as Koa from 'koa';
const app = new Koa();

这样在 TypeScript 里等于直接实例化命名空间,虽然可以使用,但是有些不合规范。符合习惯的使用方法应该是这样的:

import Koa from 'koa';
const app = new Koa();

但是这样无法运行成功,提示:

TSError: ⨯ Unable to compile TypeScript:
src/app.ts:4:8 - error TS1259: Module '"./node_modules/@types/koa/index"' can only be default-imported using the 'esModuleInterop' flag
This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

这个主要是 cjs 没有 ecm 的“默认导出”造成的不兼容问题,需要额外的转化,开启 esModuleInterop:true 即可运行成功。TypeScript 实际编译过程如下:

 // before
 import Koa from 'koa';
 
 // after 代码经过简化
 var Koa = __importDefault(require('koa'));


三, TypeScript 热加载

package.json 如下设置即可:

"scripts": {
  "dev1": "nodemon --watch ./src/app.ts -e ts,tsx --exec ts-node ./src/app.ts",
  "dev": "nodemon  --watch ./src/app.ts"
}



声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
随机推荐
WordPress关闭自动草稿
WordPress 修改 RESTful API 的请求和响应
Debian11 安装笔记3:安装 MySQL 5.7
WordPress 函数 add_option()、get_option() 和 update_option()
CRSF 跨站脚本攻击已死,使用 Same-Site Cookies 来防范 CSRF
Node.js MySQL2 如何编写事务
冒泡法排序
WordPress 实现自定义 Ajax 请求