【问题标题】:Typescript own module not found找不到打字稿自己的模块
【发布时间】:2019-03-27 23:21:58
【问题描述】:

我目前正在学习 TypeScript 并尝试定义自己的类型。我目前正在使用 .d.ts 文件来声明我的类型。

我创建了一个文件./src/typings/git-types.d.ts

declare module "git-types" {
    export interface GitRepoListItem {
        repoName: string;
        repoPath: string;
    }

    export interface GitReturnObject {
        value: any;
        errorCode: GitErrorCode;
    }

    export enum GitErrorCode {
        UnknownError = 1,
        GitNotFound = 2,
        NoValidPathGiven = 3,
        LocalChangesPreventCheckout = 4,
        LocalChangesPreventPull = 5
    }

    export interface GitCommit {
        hash: string;
        author: string;
        commitDate: string;
        commitTime: string;
        commitMessage: string;
    }
}

现在我尝试导入这个模块,以便在另一个文件 CommitHistory.ts 中使用我的类型:

import { GitCommit } from "git-types";

class CommitHistory {
    commitList: GitCommit[] = [];

    ...
}

但是当我尝试运行我的代码时,编译器失败并给我以下错误: Module not found: Can't resolve 'git-types' in './src/CommitHistory.ts

正如你在我的tsconfig.json-file 中看到的,整个“src”文件夹都包含在内:

{
    "compilerOptions": {
        "target": "es6",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "preserve",
        "experimentalDecorators": true
    },
    "include": ["src"]
}

如何声明模块才能使用我的类型?

【问题讨论】:

  • d.ts 文件由 typescript 编译器从您的 .ts 文件生成。您不会导入 d.ts 文件,编译器使用这些文件来告诉它哪些类型适用于您 imported 的任何模块。

标签: javascript reactjs typescript


【解决方案1】:

不要将您的类型声明为来自全局模块

src/typings/git-types.d.ts中,不必写declare module "git-types"。只需导出您的类型:

// src/typings/git-types.d.ts
export interface GitRepoListItem {
    repoName: string;
    repoPath: string;
}
// …

然后,这些类型可以通过相对路径导入:

// src/CommitHistory.ts
import { GitCommit } from "./typings/git-types";

或者,为现有的全局模块声明类型

如果你安装了一个真正的 npm 包git-types,它只包含 JavaScript 代码,并且你想自己提供类型,那么你的代码很好,应该可以工作。

【讨论】:

  • 感谢您的帮助。现在直接导出类型对我有用。然而,正如乙烷在他的评论中所说,我不得不将git-types.d.ts 文件重命名为git-type.ts
  • @Psycho 不,您不必重命名。扩展名.d.ts 更适合仅包含类型的文件,因为编译器不会为这些文件生成文件。
猜你喜欢
  • 2021-01-07
  • 2013-12-30
  • 2018-06-27
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
相关资源
最近更新 更多