TypeScript - 配置說明


Posted by Bryan9411 on 2021-05-14

一般來說,編輯器啟動時,會先讀取tsconfig.json這支檔案獲取相關的設定說明,如下圖所示:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

現在我們來說明一下常用的 tsConfig 設定

  1. target: "es5"
    tearget 定義了編譯後 JavaScript 版本,例如目前主流瀏覽器只可讀取到 es5 ,那透過 target 這項設定可以讓你的程式碼編譯為 es5,這樣就可被主流瀏覽器讀取,那如果不是要給瀏覽器讀取,而是 react-native 做手機 app ,那就可以選擇編譯為 es6,除了 es5 和 es6 外,還有其他常見選項,像是 Es2016 / Es2017 ...等等。

  2. lib: [ "dom", "dom.iterable", "esnext" ]
    lib 可以定義在編譯期間需要被包括進來的文件,透過這些文件,可以讓 TypeScript 知道可以使用哪些功能,比如說執行 document.getElementById("root") 這句話時,TypeScript 編譯器就會知道該如何進行檢查,如果不設置的話,一般來說默認是 ["dom", "es6","DOM.Iterable"]

  3. allowJs: true
    允許混合編譯 JavaScript 文件

  4. esModuleInterop: true
    允許使用 commonjs 方式 import 默認文件。例如 import React from 'react'

  5. jsx: react
    允許編輯器可以編譯 react jsx 語法

  6. include": ["src/**/*"]
    透過 include 列出需要編譯的文件,文件路徑需要 "相對路徑" or "絕對路徑"


#TypeScript







Related Posts

簡明 C 語言入門教學

簡明 C 語言入門教學

Day 113

Day 113

串串AIP Again~

串串AIP Again~


Comments