简体   繁体   English

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

[英]Importing custom declaration files with TypeScript

I have the following TypeScript declaration for an npm package named foo which (let just assume for the sake of this example) does not have a declaration file anywhere that I can pull. 对于名为foo的npm包,我有以下TypeScript声明(该示例中仅作假设)在我可以拉到的任何地方都没有声明文件。

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

I have placed that declaration inside ./typings/foo.d.ts file and updated my typeRoots folders to below (inside ./tsconfig.json file): 我已将该声明放置在./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"
    ]
}

and I have tried to use it from a .ts like below: 而且我尝试从如下的.ts使用它:

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

However, it was not able to resolve this. 但是,它无法解决此问题。 It was complaining to me inside VS Code, too (since I had noImplicitAny: true , I suppose, considering this ). 它也在VS Code中向我抱怨(因为我有noImplicitAny: true ,考虑到 )。

I have changed my consuption to below and it worked out: 我将消费更改为以下内容,并得出了结论:

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

Do I really need that reference declaration? 我真的需要reference声明吗? I am expecting that I don't since I have specified the ./typings folder as one of my typeRoots but it's possible that I have configured it wrong somehow. 我期待,我没有,因为我已经指定./typings文件夹作为我的一个typeRoots ,但它可能是我不知怎么配置是错误的。 Any thoughts on what I am doing wrong? 对我在做什么错有任何想法吗?

I am using TypeScript 2.2.1. 我正在使用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