使用VS Code開啟專案資料夾,輸入指令建立Node.js專案
npm init -y
此指令會建立 package.json
檔案,為JavaScript的套件設定檔
設定npm run build的欄位,修改 package.json
的scripts
欄位
"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: 找不到引用檔,型別錯誤..),仍然會產出檔案
完成以上環境設定後,進到Run的設定,點選齒輪產生 launch.json
設定檔
改為以下內容即可
"configurations": [
{
"type": "node-terminal",
"name": "Run Script: build",
"request": "launch",
"command": "npm run build",
"cwd": "${workspaceFolder}"
}
]
參考來源:
1.在Node.js專案中使用TypeScript
透過 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
要自行手動移除不需要對外公開的方法或屬性
參數用途
參考文件
Managing External Tools
Developer Command Prompt for Visual Studio
Node.js
Declaration Files