TypeScript_Getting_started_In_VSCode

初始設定

# 初始化會產出package.json
npm init  
# 安裝 Typescript
npm install i -g typescript
# 確認是否有安裝成功
tsc --version
# 建立設定檔案
tsc --init --sourceMap --rootDir src --outDir dist        
// 主要在 tsconfig.json 設定,所以自行在專案底下產生src & dist 
{
  "compilerOptions": {
      "rootDir": "src", /* Specify the root folder within your source files. */
      "outDir": "dist", /* Specify an output folder for all emitted files. */
  }
}  

執行ts會出現以下錯誤,主要是沒有編譯,編譯過後,dist資料夾底下就會有 編譯過後的js

# 執行ts會出現以下錯誤

Uncaught SyntaxError D:\Typescript\Hello_World\src\index.ts:1 
import { Chicken } from './chicken'; 
^^^^^^ 
SyntaxError: Cannot use import statement outside a module

# 主要是沒有編譯,編譯過後,dist資料夾底下就會有 編譯過後的js

PS D:\Typescript\Hello_World> tsc
PS D:\Typescript\Hello_World> ls dist


    Directory: D:\Typescript\Hello_World\dist

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---         2023/5/18 上午 09:34            233 chicken.js
-a---         2023/5/18 上午 09:34            201 chicken.js.map
-a---         2023/5/18 上午 09:34            236 index.js
-a---         2023/5/18 上午 09:34            229 index.js.map

變更程式進入點

launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\\dist\\index.js",
            //"program": "${workspaceFolder}\\src\\index.ts", // 原本
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}

使用Tasks Watch 監控檔案異動

每次變更都要使用 tsc編譯太麻煩了,所以執行以下指令讓每次執行F5都自動編譯

{

  "name": "hello_world",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^5.0.4"
  }
}

F1 --> Tasks:Configure Default Build Task
200-Areas/250-程式語言/Typescript/resource/Getting_started.png
選擇 tsc: watch -tsconfig.json
200-Areas/250-程式語言/Typescript/resource/Getting_started-1.png
選擇 Tasks: Run Build Task
200-Areas/250-程式語言/Typescript/resource/Getting_started-2.png

就會開始監控檔案變更自動編譯
200-Areas/250-程式語言/Typescript/resource/Getting_started-3.png