使用ts 開發node.js 項目 搭建入門項目


1. 初始化項目

  npm init  生成 package.json 文件

{
  "name": "node.redis",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

2. 安裝  node 模塊的 ts 聲明文件

  npm install --save typescript  (需要確認)

  npm i --save @types/node

    安裝 @types/node 以后, node 會有對應的ts 聲明,並且 vscode 可以提供相應的代碼感知

    安裝前:

        

    安裝后:

        

3.  npm 第三方庫 的 ts 支持

  以 restify 為例.

  3.1. 安裝 restify 依賴

    npm i --save restify

    server.js 中引用 restify 成功:

    

    server.ts 中 import restify 時失敗,此時還沒有安裝 restify 的 ts 引用.

    

  3.2 安裝 restify ts 依賴.(為js 庫,提供 index.d.ts 聲明)

    npm i --save @types/restify

    

4. 編譯 運行 ts 項目

  4.1 編譯 ts

    生成 tsconfig.json 文件: tsc --init 

{
  "compilerOptions": {
      "module": "commonjs", //指定生成哪個模塊系統代碼
      "target": "es6", //目標代碼類型
      "noImplicitAny": false, //在表達式和聲明上有隱含的'any'類型時報錯。
      "sourceMap": true, //用於debug   
      "rootDir": "./src", //根目錄
      "outDir": "./build", //重定向輸出目錄。   
      "watch": true //在監視模式下運行編譯器。會監視輸出文件,在它們改變時重新編譯。
  }
}

  4.2 vscode 編譯

    菜單 -> 任務 -> Run Build task -> tsc: build - tsconfig.json;

    運行 node build/server.js

  4.3  使用 ts-node 

    安裝 ts-node: npm  install -g ts-node

    配置 vscode 調試 launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "調試 TS Node 程序 - args",
            "type": "node",
            "request": "launch",
            "runtimeExecutable": "node",
            "runtimeArgs": [
                "-r",
                "ts-node/register"
            ],
            "args": [
                "${workspaceFolder}/src/index.ts"
            ]
        }
    ]
}

    參考:https://www.barretlee.com/blog/2019/03/18/debugging-in-vscode-tutorial/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM