欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js項(xiàng)目中添加ts支持實(shí)現(xiàn)示例詳解

 更新時(shí)間:2023年08月03日 10:57:48   作者:寫(xiě)代碼的寶哥  
這篇文章主要為大家介紹了如何在js項(xiàng)目中添加ts支持實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

安裝 TypeScript 依賴(lài)

首先安裝 TypeScript 依賴(lài),我們要通過(guò) tsc 指令創(chuàng)建聲明文件:

pnpm install -D typescript

創(chuàng)建配置文件

接下來(lái)創(chuàng)建 TypeScript 配置文件:

npx tsc --init

這一步會(huì)在項(xiàng)目的根目錄下創(chuàng)建一個(gè) tsconfig.json 文件。我們?cè)谠瓉?lái)配置的基礎(chǔ)上開(kāi)放一些配置:

{
  "compilerOptions": {
     "target": "es2016",
     "module": "commonjs",
     "esModuleInterop": true,
     "forceConsistentCasingInFileNames": true,
     "strict": true,
     "noImplicitAny": false,
     "skipLibCheck": true,
+    "allowJs": true,
+    "checkJs": true,
+    "declaration": true,
+    "emitDeclarationOnly": true,
+    "rootDir": "./",
+    "outDir": "./types",
   }
+  "include": [
+    "security/**/*"
+  ]
}

字段說(shuō)明

對(duì)上述字段,我們挑幾個(gè)重要的說(shuō)明一下。

  • allowJs、checkJs 增加 JS 文件支持
  • declaration、emitDeclarationOnly 我們只需要 tsc 幫我們生成類(lèi)型聲明文件即可
  • rootDir、outDir 指定了類(lèi)型聲明文件生成到 types/ 目錄
  • include 我們只為 security/ 目錄下的代碼生成類(lèi)型聲明文件

想詳細(xì)了解每個(gè)配置字段的含義,可以參考 TypeScript 官方說(shuō)明:https://aka.ms/tsconfig。

生成類(lèi)型文件

項(xiàng)目根目錄下創(chuàng)建 index.d.ts 文件

export let security: typeof import("./types/security");

接下里修改 package.json, 增加當(dāng)前 npm 包的類(lèi)型聲明支持和構(gòu)建腳本 typecheck

{
    "scripts": {
        // ...
        "typecheck": "tsc",
    },
    types: "index.d.ts"   
}

接下來(lái)執(zhí)行腳本:

npm run typecheck

最后就能看到在 types/ 目錄下為 security/ 生成的類(lèi)型聲明文件了。

以上就是js項(xiàng)目中添加ts支持實(shí)現(xiàn)示例詳解的詳細(xì)內(nèi)容,更多關(guān)于js項(xiàng)目添加ts支持的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論