使用typescript開發node js

一、typescript helloworld

參考
TypeScript(入門)

1.安裝node,npm,typescript,vs code等
2.新建一個目錄,比如tsHelloworld,使用命令行運行tsc --init,tsc會幫助我們創建一個tsconfig.json文件,tsconfig是tsc每次編譯時都會檢查的一個配置文件。這里可以參考tsconfig.json官方文檔

命令行運行code .,使用vs code打開項目。

image.png

rootDir,outDir默認被 注釋掉了,一個是源文件目錄,一個是編譯后生成的JS目錄。在tsHelloworld下新建兩個文件夾:bin,src,然后更改相應的配置。
3.在VS CODE任務主菜單下,選擇運行生成任務,或者使用CTRL+SHIFT+B
image.png

這里可以參考tsconfig.json官方文檔

選擇tsc:構建,控制 臺會報錯,這是因為src目錄下找不到ts文件。

> Executing task: tsc -p e:\node\tsHelloworld\tsconfig.json <

error TS18003: No inputs were found in config file 
'e:/node/tsHelloworld/tsconfig.json'. Specified 'include' 
paths were '["**/*"]' and 'exclude' paths were '[]'.

在src目錄下,新建一個Hello.ts的文件:

class Hello {
    firstName : string;
    lastName : string;
    constructor(fiestName : string,  lastName : string) {
        this.firstName = fiestName;
        this.lastName = lastName;
    }
    greeter() {
        return "歡迎來到typescript的世界,hello" +
         this.firstName + " " + this.lastName;
    }
}
var user = new Hello("王", "小二");
document.body.innerHTML = user.greeter();

然后再使用tsc:構建,可以發現bin目錄下多出一個Hello.js文件。
4.在bin目錄下,新建index.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Word</title>
</head>
<body>
    <script src="Hello.js"></script>
</body>
</html>

現在,可以運行index.html文件看一下頁面了。

二、ts開發node.js

typescript 開發node 可行么? 會存在什么問題
TypeScript在node項目中的實踐
【學習筆記】在VSCode上配置typescript + nodejs 開發環境
這里部分參考本文第一部分的helloworld內容
1.新建ts-node-starter文件夾,命令行運行tsc --init,然后使用code .打開vs code。tsc:構建配置一下,打開tasks.json
2.tsconfig.json把sourceMap打開
3.debug配置,打開launch.json。這里可以參考node js調試相關

    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "啟動程序",
            "program": "${workspaceRoot}/app.ts"
        }
    ]

4.新建app.ts

import { createServer, Server, IncomingMessage, ServerResponse } from 'http';
// 明確類型麻煩些,卻會獲得非常詳細的語法提示
 
const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/plain");
    res.end("Hello World\n");
})

const hostname: string = "127.0.0.1";
const port: number = 3000;
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
})

關于import,還是require,參考 Typescript import/as vs import/require? [duplicate]
參考在nodeJs的Express框架下用TypeScript編寫router路由出現import關鍵字錯誤的解決方案

其實這里只是import變成了var而已,但其意義在于在ts代碼中采用import載入的模塊可以享用強類型檢查,以及代碼自動補全,預編譯檢查等。

5.編譯成js后,可以斷點調試了。
6.代碼提示typings
參考代碼提示Typings,這里區別有點大,import { createServer, Server, IncomingMessage, ServerResponse } from 'http';都認不出來。不像寫JS的時候,直接typings init就行了。

E:\node\ts-node-starter> typings install node --ambient --save
typings ERR! deprecated The "ambient" flag
 is deprecated. Please use "global" instead
E:\node\ts-node-starter> typings install node --global --save

沒辦法,只能把node安裝進來。參考使用TypeScript編寫node項目的疑惑。這時可以看到typings.json變成這樣:

{
  "dependencies": {},
  "globalDependencies": {
    "node": "registry:dt/node#7.0.0+20170322231424"
  }
}

這時候再寫import * as http from 'http';就可以進入代碼提示了。
7.@types
參考在 Typescript 2.0 中使用 @types 類型定義
使用Typescript開發node.js項目——簡單的環境配置

在 Typescript 2.0 之后,TypeScript 將會默認的查看 ./node_modules/@types 文件夾,自動從這里來獲取模塊的類型定義,當然了,你需要獨立安裝這個類型定義。比如,你希望 core.js 的類型定義,那么,你需要安裝這個庫的定義庫。
npm install --save @types/core-js
與我們安裝一個普通的庫沒有區別。當然了,常用的 jquery 也有。Microsoft 在 The Future of Declaration Files 介紹了 TypeScript 的這個新特性。

在項目目錄下執行安裝:npm install --save-dev @types/node就可以獲得有關node.js v6.x的API的類型說明文件。之后,就可以順利的導入需要的模塊了:import * as http from 'http';完成之后,不僅可以正常的使用http模塊中的方法,也可以在vscode中獲得相應的代碼提示。

對于內建模塊,安裝一個@types/node模塊可以整體解決模塊的聲明文件問題。那么,對于浩如煙海的第三方模塊,該怎么辦呢?官方和社區中也提供了查找和安裝的渠道:

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容