在编译输出中包括外部类型定义

时间:2018-07-13 07:48:48

标签: typescript yarn-workspaces

我正在使用TypeScript @cjol/core编写一个库。它具有JavaScript依赖项dep,没有@types包可用。相反,我编写了一个自定义dep.d.ts文件,这使我在开发库时所有键入都能很好地工作。一切都可以正常编译,但是我的dep.d.ts不会出现在输出中的任何地方。

当我尝试将库包含在另一个客户端项目@cjol/client中时,该客户端项目将无法编译。我收到这样的错误:

../core/build/index.d.ts:2:24 - error TS7016: Could not find a declaration file for module 'dep'. '/home/cjol/.../dep/index.js' implicitly has an 'any' type.
  Try `npm install @types/dep` if it exists or add a new declaration (.d.ts) file containing `declare module 'dep';`

2 > import { Foo } from "dep";

我还使用了Yarn工作区(@cjol/core@cjol/client都在同一工作区中,位于./core./client下的程序包),但我认为那不是在这里相关。我需要@cjol/client来输出我的自定义定义文件,但是我不知道如何实现它!


编辑1:同样,我不确定细节是否相关,但这就是index.d.ts的样子。如前所述,它是由TypeScript生成的。

import { Stuff } from "a-typescript-library";
import { Foo } from "dep";

export * from "./my-app-types";

declare type APIResponse<T> = {
    /* ... */
};
export declare class API {
    /* ... */
}

编辑2:dep.d.ts如下所示:

declare module "dep" {
  import Something from "something.js";
  export class DepClass {
     /* loads of stuff */
  }
}

编辑4:也许是对我的问题的另一种思考方式。如果我编写了自定义.d.ts文件,该如何分发?我需要创建一个包含类型定义的全新软件包吗?

2 个答案:

答案 0 :(得分:1)

不幸的是,打字稿不会将您的自定义 *.d.ts 文件复制到您的输出中。不过,您可以通过多种方式解决此问题。

首先,在您完成运行 *.d.ts 并确保目录结构与其在 tsc 目录中的情况相匹配后,手动将您的自定义 src 文件复制到您的输出目录中。< /p>

另一种选择是将 dep.d.ts 文件重命名为 dep.ts 文件并将其包含在需要该类型的模块中。

文件现在称为 dep.ts

declare module "dep" {
  import Something from "something.js";
  export class DepClass {
     /* loads of stuff */
  }
}

dep.ts 导入需要它的模块。

import './types/dep';
import { Foo } from 'dep';

// Rest of your code here

答案 1 :(得分:0)

好吧,我想我知道像以前一样发生的事情。我敢打赌,您没有在项目的dep.d.ts定义位置创建baseUrl。在基本根目录中声明的任何模块都将由TypeScript自动提取,其他任何内容都需要映射到tsconfig.json中。此属性称为path-路径映射。

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

示例tsconfig.json如果使用正确的映射信息将paths属性添加到此配置文件中,它将解决您的问题。

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "dep": ["src/typings/dep"] // That location is a example but you need to point that at where your dep.d.ts file is
    }
  }
}