[TS] TypeScript Getting Started
此篇為各筆記之整理,非原創內容,資料來源可見下方連結與文後參考資料。
CLI
$ npm init -y # 初始化 npm
$ npm install -D typescript # 安裝 typescript
$ npx tsc --init # 產生 TS 設定檔 tsconfig.json
$ npx ts-node index.ts
# 將 TS 編譯成 JS
$ tsc # Run a compile based on a backwards look through the fs for a tsconfig.json
$ tsc index.ts
$ tsc src/*.ts # Transpile any .ts files in the folder src, with the default settings
$ tsc --watch # 常駐使用語法檢測
- ts-node-dev:當檔案有變更時能夠自動重啟(不是自動重新打包)
- ts-node:不需重新打包就可以直接執行 ts 檔
For Development
透過 nodemon 搭配 ts-node 自動 reload 與編譯
How to watch and reload ts-node when TypeScript files change @ stackOverflow
在根目錄建立 nodemon.json
,並撰寫以下設定:
// nodemon.json
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "npx ts-node ./src/index.ts"
}
使用 ts-node 的注意事項
使用 ts-node
時需要留意在 tsconfig.json
中的 module
是否有設定為 "module": "commonjs"