使用 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
生成的文件可以直接与 njs 一起使用。test.js