繁体   English   中英

找不到打字稿自己的模块

[英]Typescript own module not found

我目前正在学习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"]
}

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

不要将您的键入内容声明为来自全局模块

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";

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

如果您安装了仅包含JavaScript代码的真实npm包git-types ,并且希望自己提供类型,那么您的代码就可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM