使用 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 一起使用。