【问题标题】:Importing custom declaration files with TypeScript使用 TypeScript 导入自定义声明文件
【发布时间】:2017-07-21 02:52:21
【问题描述】:

我有一个名为 foo 的 npm 包的以下 TypeScript 声明(假设为了这个例子)在任何我可以拉取的地方都没有声明文件。

declare module "foo" {
    export function getPerpetualEnergy(): any[];
    export function endWorldHunger(n: boolean): void;
}

我已将该声明放在./typings/foo.d.ts 文件中,并将我的typeRoots 文件夹更新到下面(在./tsconfig.json 文件中):

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "strictNullChecks": true,
        "moduleResolution": "node",
        "typeRoots": [
            "./typings/",
            "./node_modules/@types/"
        ]
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.test.ts"
    ]
}

我已经尝试通过.ts 使用它,如下所示:

import * as foo from 'foo';
foo.endWorldHunger(true);

但是,它无法解决此问题。它也在 VS Code 中向我抱怨(因为我有 noImplicitAny: true,我想,考虑到 this)。

我已将我的消耗更改为以下内容,并且成功了:

/// <reference path="../../typings/foo.d.ts"/>
import * as foo from 'foo';
foo.endWorldHunger(true);

我真的需要reference 声明吗?我希望我不会,因为我已将 ./typings 文件夹指定为我的 typeRoots 之一,但我可能以某种方式将其配置错误。关于我做错了什么有什么想法吗?

我使用的是 TypeScript 2.2.1。

【问题讨论】:

    标签: javascript typescript visual-studio-code


    【解决方案1】:

    用作typeRoots 的目录应该看起来像node_modules 目录,也就是说,你的foo 声明文件应该在typings/foo 文件夹中并命名为index.d.ts(或者你应该有package.jsontypings/foo 中,types 属性指向声明文件)。

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 2020-01-30
      • 1970-01-01
      • 2020-11-22
      • 2018-05-04
      • 2020-04-09
      • 2017-07-30
      • 2021-05-01
      • 1970-01-01
      相关资源
      最近更新 更多