使用 TypeScript 定义文件编写 njs 代码
编译 TypeScript 定义文件 API 检查和自动补全 编写类型安全的 njs 代码 |
TypeScript 是 JavaScript 的一个带类型超集,它可以编译成纯 JavaScript。
TypeScript 支持定义文件,这些文件包含现有 JavaScript 库的类型信息。这使得其他程序能够使用文件中定义的值,就好像它们是静态类型的 TypeScript 实体一样。
njs 提供了用于其 API 的 TypeScript 定义文件,这些文件可用于
- 在编辑器中获取自动补全和 API 检查
- 编写类型安全的 njs 代码
编译 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 一起使用。