如何为你的 js 项目添加 ts 支持?

发布时间 2023-08-02 20:30:15作者: 写代码的宝哥

前一段时间为公司内的一个 JS 公共库,增加了一些 TypeScript 类型支持。在这里简答记录一下。

安装 TypeScript 依赖

首先安装 TypeScript 依赖,我们要通过 tsc 指令创建声明文件:

pnpm install -D typescript

创建配置文件

接下来创建 TypeScript 配置文件:

npx tsc --init

这一步会在项目的根目录下创建一个 tsconfig.json 文件。我们在原来配置的基础上开放一些配置:

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

字段说明

对上述字段,我们挑几个重要的说明一下。

  • allowJscheckJs 增加 JS 文件支持
  • declarationemitDeclarationOnly 我们只需要 tsc 帮我们生成类型声明文件即可
  • rootDiroutDir 指定了类型声明文件生成到 types/ 目录
  • include 我们只为 security/ 目录下的代码生成类型声明文件

想详细了解每个配置字段的含义,可以参考 TypeScript 官方说明:https://aka.ms/tsconfig

生成类型文件

项目根目录下创建 index.d.ts 文件

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

接下里修改 package.json, 增加当前 npm 包的类型声明支持和构建脚本 typecheck

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

接下来执行脚本:

npm run typecheck

最后就能看到在 types/ 目录下为 security/ 生成的类型声明文件了。

本文由mdnice多平台发布