Appearance
使用 TypeScript 定义文件编写 njs 代码
提示
来自deepseek解释
原文链接:https://nginx.org/en/docs/njs/typescript.html
TypeScript 是 JavaScript 的类型化超集,可编译为纯 JavaScript。TypeScript 支持定义文件,其中包含现有 JavaScript 库的类型信息。这使得其他程序能够像使用静态类型的 TypeScript 实体一样,使用这些文件中定义的值。njs 为其 API 提供了 TypeScript 定义文件,可用于:
- 在编辑器中获得自动补全和 API 检查
- 编写类型安全的 njs 代码
编译 TypeScript 定义文件
bash
$ 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.tsAPI 检查与自动补全
将 *.d.ts 文件放置到编辑器可以找到的位置。
test.js:
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:
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 安装:
bash
# npm install -g typescriptTypeScript 编译:
bash
$ tsc test.ts
$ cat test.js生成的 test.js 文件可直接与 njs 一起使用。