Try   HackMD

產生TypeScript的declare檔案

透過Node.js

使用VS Code開啟專案資料夾,輸入指令建立Node.js專案

npm init -y

此指令會建立 package.json檔案,為JavaScript的套件設定檔

設定npm run build的欄位,修改 package.jsonscripts欄位

"scripts": {
    "build": "tsc -d",
    "start-dev": "npm run build -- --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

安裝typescript套件

npm i -D typescript

-D參數即save-dev參數,表示此套件只使用在這個專案

建立TypeScript的設定檔: tsconfig.json

tsc --init

修改內容,指定要編譯的檔案(若不設定files,專案內所有檔案都會產出.d.ts)

{
  "compilerOptions": {
    "target": "ES6"
  },
  "files": [
    "index.ts"
  ]
}

執行編譯,即可產出declaration files(.d.ts)

npm run build

PS. 就算編譯失敗(ex: 找不到引用檔,型別錯誤..),仍然會產出檔案

VSCode內F5一鍵執行

完成以上環境設定後,進到Run的設定,點選齒輪產生 launch.json 設定檔

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

改為以下內容即可

"configurations": [
        {
            "type": "node-terminal",
            "name": "Run Script: build",
            "request": "launch",
            "command": "npm run build",
            "cwd": "${workspaceFolder}"
        }
    ]

參考來源:
1.在Node.js專案中使用TypeScript


純 command 執行

  • 首次安裝

透過 npm 安裝 typescript

npm install -g typescript

啟動 compiler

npx tsc
  • 使用方法

從 ts 產生, 並且移除註解

tsc 檔名.ts -d --removecomments

從 js 產生

tsc 檔名.js -d --allowjs

由於從 js 會產生相同檔名的 js 而出現寫入錯誤 (TS5055)
可以另外指定輸出檔名或資料夾

--outfile 輸出檔名.js
--outdir 輸出資料夾

目前無法忽略 protected 和 private
要自行手動移除不需要對外公開的方法或屬性

參考來源


透過 Visual Studio 產生

  1. 透過 External Tools 的功能來執行 tsc
  2. 會抓取目前正在使用中的檔案路徑
  3. 如果要輸出檔案到不同路徑, 需要使用 tsc 的 outDir

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

參數用途

  • /k
    • 後面可執行 command
  • $(ItemPath)
    • 抓取目前正在使用中的檔案路徑
  • $(ItemDir)
    • cmd 的目錄切換到目前的檔案資料夾 (非必要)

參考文件
Managing External Tools
Developer Command Prompt for Visual Studio


tags: Node.js Declaration Files