【问题标题】:Include external type definitions in compilation output在编译输出中包含外部类型定义
【发布时间】:2018-07-13 07:48:48
【问题描述】:

我正在用 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 文件,我该如何分发它?我需要创建一个包含类型定义的全新包吗?

【问题讨论】:

  • 请粘贴您的 index.d.ts
  • 我不确定这会有多大帮助,但我现在已经添加了。
  • 对不起,你能粘贴你的 dep.d.ts
  • 已经完成了,但又一次——我认为这些文件的细节没有必要。关键是它没有包含在编译输出中,我不知道为什么。
  • 不幸的是,它不是我出于其他原因放弃的一个爱好项目。如果有答案,仍然渴望找到答案!

标签: typescript yarn-workspaces


【解决方案1】:

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

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

另一种选择是将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

【讨论】:

    【解决方案2】:

    好吧,我想我知道这里发生了什么,就像我之前遇到的一样。我打赌你没有在项目的baseUrl 定义的位置创建你的dep.d.ts。在基本根目录中声明的任何模块都将被 TypeScript 自动拾取,其他任何内容都需要在 tsconfig.json 中映射。此属性称为path - 路径映射。

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

    例如tsconfig.json 如果您使用正确的映射信息将路径属性添加到此配置文件,它应该可以解决您的问题。

    {
      "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
        }
      }
    }
    

    【讨论】:

    • 感谢您对此进行调查。我已经尝试过了,但我看不出它有什么不同。如果我检查编译输出,我应该能够在某处找到dep.d.ts,不是吗?
    猜你喜欢
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 2017-06-08
    相关资源
    最近更新 更多