使用 TypeScript 定义文件编写 njs 代码

编译 TypeScript 定义文件
API 检查与自动补全
编写 njs 类型安全代码

TypeScript 是 JavaScript 的一个强类型超集,可编译为纯 JavaScript。

TypeScript 支持包含现有 JavaScript 库类型信息的定义文件。这使得其他程序可以像使用静态类型 TypeScript 实体一样使用这些文件中定义的数值。

njs 为其 API 提供了 TypeScript 定义文件,可用于:

编译 TypeScript 定义文件

$ git clone https://github.com/nginx/njs
$ cd njs && ./configure && make ts
$ ls build/ts/
njs_core.d.ts
njs_shell.d.ts
ngx_http_js_module.d.ts
ngx_stream_js_module.d.ts

API 检查与自动补全

*.d.ts 文件放置在编辑器可以找到的位置。

test.js:

/// <reference path="ngx_http_js_module.d.ts" />
/**
 * @param {NginxHTTPRequest} r
 * */
function content_handler(r) {
    r.headersOut['content-type'] = 'text/plain';
    r.return(200, "Hello");
}

编写 njs 类型安全代码

test.ts:

/// <reference path="ngx_http_js_module.d.ts" />
function content_handler(r: NginxHTTPRequest) {
    r.headersOut['content-type'] = 'text/plain';
    r.return(200, "Hello from TypeScript");
}

TypeScript 安装

# npm install -g typescript

TypeScript 编译

$ tsc test.ts
$ cat test.js

生成的 test.js 文件可直接与 njs 一起使用。