建立tsconfig檔做設定


Posted by mijouhsieh on 2024-07-17

指令
tsc --init

回傳
Created a new tsconfig.json with:   
  target: es2016
  module: commonjs
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true

You can learn more at https://aka.ms/tsconfig
  • 指定TS專案最後輸出的目標JS版本是什麼 “target”: “es2016“
  • 指定哪一種module的方式做應用 “module”: “commonjs“
  • 指定專案目錄 “rootDir”: “./“(教學做配置)
  • 允許使用JS檔案在TS專案中 “allowJs: true“

tsconfig檔中設定ts檔位置,和編譯後的js檔被建立的位置

資料結構 src資料夾 / index.ts檔 (要編譯index.ts檔) dist資料夾 ( 出口)
設定 “rootDir”: “./src“ “outDir”: “./dist“

編譯ts檔

VSCode TERMINAL中輸入 tsc
src資料夾 / index.ts檔

let num: number = 123

做編譯 ⇒
dist 資料夾 / 產生 index.js檔

 "use strict";
let num = 123;

若沒設定“outDir”: “./dist“ ,編譯後的js檔被建立的位置會在src資料夾中。


tsconfig檔 - inlineSourceMap 功能

  • dist 資料夾 / 新增 index.html檔 !建立模板
  • 確認 VSCode 有安裝 live server 套件
  • 在 VSCode 上方輸入>reload window 會重新開啟VSCode
  • => 右下角 藍色工具列會出現 Go Live的按鈕

    點擊 Go Live的按鈕 => 瀏覽器出現 index.html
    在本地端啟動一個開發用的server,運行index.html
    把編譯好的 index.js 引入到index.html

<html>
     //...
     <body>
      <script src="./index.js"></script>
    </body>
</html>

開發 TpeScript的流程:

  • 先寫 TpeScript
  • TpeScript 編譯器 => 編譯成 JavaScript
  • 放進 html 中執行
    // index.ts
    let num: number = 123
    console.log('num: ', num)
    

terminal : tsc

// index.js
"use strict";
let num = 123;
console.log('num: ', num);
// browser console
num: '123

tsconfig檔 - inlineSourceMap 功能

=> 方便debug,顯示typescript檔中code的位置

browser console中顯示的 num: '123 右邊有 index.js
說明 console.log 是在檔案中的哪一行

我們用 typescript 檔案做開發
但瀏覽器source是顯示編譯後的javascript

有時候會看不懂編譯後的樣子(?
=> 完整指定 typescript中寫code的位置

  • “inlineSourceMap“: true 開功能

setInlineSourceMap.png


#tsconfig







Related Posts

MTR04_0707

MTR04_0707

Web 資訊安全(Security)簡明入門教學指南

Web 資訊安全(Security)簡明入門教學指南

第二周筆記 (JS) -4

第二周筆記 (JS) -4


Comments