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

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

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

安裝 TypeScript 依賴

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

pnpm install -D typescript

創(chuàng)建配置文件

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

npx tsc --init

這一步會在項目的根目錄下創(chuàng)建一個 tsconfig.json 文件。我們在原來配置的基礎(chǔ)上開放一些配置:

{
  "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/**/*"
+  ]
}

字段說明

對上述字段,我們挑幾個重要的說明一下。

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

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

生成類型文件

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

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

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

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

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

npm run typecheck

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

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

相關(guān)文章

最新評論