Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

雖說用 Node 是經常的事情,但還是第一次嘗試用 Typescript 寫 NodeJS 程式。今天想寫一個簡單的網站,這裡記錄一下這個簡單的過程。

所需的是 TypeScript 編譯器以及對應的類型定義,我這戲需要用到 Express,所以 Express 和其類型定義也需要安裝。

1
2
npm install express
npm install typescript ts-node @types/node @types/express --save-dev

然後需要新建 tsconfig.json 用於描述這個 TypeScript 專案。可以沿用以前的設定,或使用以下命令常見模板設定。

1
npx tsc --init

之後就會出現一個帶著註釋的 json 文件。可以按需調配。我需要用到的東西如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"compilerOptions": {

/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* 程式碼檔案的根目錄. */

/* Emit */
"outDir": "./dist", /* JavaScript 檔案的輸出位置. */

/* Interop Constraints */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type

/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

每次編寫好後都需要編譯成 JavaScript 檔才能被 NodeJS 執行,編譯很簡單:

1
2
              # 專案根目錄
tsc --project ./

那麼就把這句話直接塞進 package.json

1
2
3
4
5
6
7
8
{   
/* ... */
"scripts": {
"build": "tsc --project ./", /* 構建 */
"start": "node dist/index.js" /* 運行 */
},
/* ... */
}

於是便可以愉快地有(類)型地寫代碼了:

1
2
3
4
5
6
7
8
9
10
11
12
import express from 'express';

const app = express()

app.get("/", (request, response) => {
response.write("Hello world!")
response.end()
});

app.listen(8080, () => {
resolve()
})

评论