On this page
使用 TypeScript 定义文件编写 njs 代码
TypeScript是 JavaScript 的类型化超集,可编译为纯 JavaScript。
TypeScript 支持包含现有 JavaScript 库的类型信息的定义文件。这使其他程序可以使用文件中定义的值,就像它们是静态键入的 TypeScript 实体一样。
njs 为其API提供 TypeScript 定义文件,可用于:
在编辑器中获取自动补全和 API 检查
编写 NJS 类型安全代码
编译 TypeScript 定义文件
$ hg clone http://hg.nginx.org/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 installation:
# npm install -g typescript
TypeScript compilation:
$ tsc test.ts
$ cat test.js
生成的test.js
文件可以直接与 njs 一起使用。