繁体   English   中英

使用TypeScript导入自定义声明文件

[英]Importing custom declaration files with TypeScript

对于名为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 ,考虑到 )。

我将消费更改为以下内容,并得出了结论:

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

我真的需要reference声明吗? 我期待,我没有,因为我已经指定./typings文件夹作为我的一个typeRoots ,但它可能是我不知怎么配置是错误的。 对我在做什么错有任何想法吗?

我正在使用TypeScript 2.2.1。

作为目录typeRoots应该看起来像node_modules目录,也就是你的申报文件foo应该在typings/foo文件夹并命名为index.d.ts (或你应该package.jsontypings/footypes物业指向声明文件)。

暂无
暂无

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

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