【问题标题】:How to use declaration for 3th party module如何使用第 3 方模块的声明
【发布时间】:2018-11-09 21:43:07
【问题描述】:

我正在使用fingerprintjs2 库,它在definitelyTyped 中有不完整且不兼容的声明

我选择在我的项目中编写自己的声明,但我正在努力在代码中加载该声明。我仍然收到错误

找不到模块'fingerprintjs2'

在这个导入语句中

import Fingerprint2, { TCallback, TComponent } from 'fingerprintjs2';

我的声明被写成独立模块

// ./src/@types/fingerprintjs2/index.d.ts

// ...some other exported types

export type TComponent = {
    key: string;
    value: string | number | boolean | string[];
};

export type TCallback = (components: TComponent[]) => void;

export default interface fingerprintjs2 {
    get(callback: TCallback): void;
    get(options: TOptions, callback: TCallback): void;
    getPromise(options: TOptions): Promise<TComponent[]>;
}

我的 tsconfig.json

{
    "include": ["src/**/*"],
    "exclude": ["node_modules"],
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "baseUrl": ".",
        "declaration": true,
        "declarationDir": "./dist",
        "lib": ["dom", "es5", "scripthost"],
        "module": "es6",
        "noImplicitAny": true,
        "outDir": "./dist",
        "paths": { "*": ["./src/@types*"] },
        "target": "es5"
    }
}

我没有找到关于这将如何工作的明确解释。你能给我一个建议吗?感谢您的帮助。

我在 Webstorm 2018.2 中使用 Typescript 3.1.6

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    您需要设置 typeRoots 以便它选择您的自定义类型文件夹。

    来源:https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

    这样的事情应该可以工作:

    "typeRoots": [
      "node_modules/@types",
      "src/@types"
    ]
    

    【讨论】:

    【解决方案2】:

    问题在于解决模块,我已更改 tscongif.json 编译器选项

    ++ "moduleResolution": "node",
    -- "paths": { "*": ["./src/@types*"] },
    ++ "paths": { "*": ["./node_modules/*", "./src/@types/*"] },
    

    然后模块就被解析了。

    我有一个错误,模块导出只是类型,这是真的,我导出了一个interface。我必须首先实现该接口,然后导出实现的值。像这样

    // declare const value with interface
    declare const fingeprint: fingerprintjs2;
    // export that const value
    export default fingeprint;
    

    现在看来可以了。

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 2021-12-06
      • 2017-10-18
      • 2023-04-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多