在nodejs中使用Typescript

1.首先新建一個項目
npm init -yes
2.開啟Typescript依賴
npm install typescript --save-dev

安裝typescript,現在我們可以通過命令行來使用tsc命令

3.安裝nodejs類型
npm install @types/node --save-dev
4.使用命令創建一個tsconfig.json文件
npx tsc --init --rootDir src --outDir build --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true

去除了無用的注釋它的內容像這樣的

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es6"],
    "module": "commonjs",
    "rootDir": "src",
    "resolveJsonModule": true,
    "allowJs": true,
    "outDir": "build",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "skipLibCheck": true                                
  }
}

rootDir: typescript尋找我們編寫代碼的地方,現在配置為src目錄,現在需要在項目錄中創建一個src文件夾編寫ts代碼

5.編寫ts代碼

新建src/index.ts文件

console.log("hello 梁典典")

執行編譯命令npx tsc,在項目目錄中會自動創建build/index.js文件,內容如下

"use strict";
console.log("hello 梁典典");
6.配置熱重載功能

它將監聽你的代碼自動進行惹更新

npm install --save-dev ts-node nodemon

項目根目錄創建nodemon.json文件

{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "ts-node ./src/index.ts"
}

package,json新增一個腳本命令

"start:dev": "nodemon"

在命令行執行npm run start:dev,就可以自動監聽文件更改了

7.創建支持清理和編譯的生成版本

安裝rimraf

npm install --save-dev rimraf

添加腳本

"build": "rimraf ./build && tsc",
8. 創建生產啟動腳本
"start": "npm run build && node build/index.js"

現在可以使用typescript編寫代碼了

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

推薦閱讀更多精彩內容