【问题标题】:How do I import a Javascript library into Typescript when the package has a declaration file当包有声明文件时,如何将 Javascript 库导入 Typescript
【发布时间】:2021-02-20 01:32:41
【问题描述】:

我正在尝试使用callbag 库中的类型定义。该库在其 package.json 中声明其类型定义文件。它没有上传到DefinitelyTyped。当我尝试导入库时,出现错误:

Cannot find module 'callbag'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?

我是这样导入的:

import type { Sink } from 'callbag';

这是我的tsconfig.json

{
  "compilerOptions": {
    "module": "es6",
    "noEmitOnError": true,
    "outDir": "./dist",
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "es5"
  },
  "include": ["./src/**/*"]
}

我也尝试将"types": ["callbag"] 添加到 tsconfig.json,但没有成功。

如何让 typescript 识别这个库的类型?

【问题讨论】:

  • 首先,您的导入语句看起来是正确的。您能否将tsconfig.json 粘贴到您的问题中(使用编辑)?
  • 这能回答你的问题吗? Typescript 2.0. "types" field in tsconfig.json
  • 我已经添加了 tsconfig.json。链接的答案对我不起作用。我用 tsconfig.json 中的类型进行了尝试。
  • @Eva 你能尝试在 tsconfig.json 中设置 "moduleResolution": "node" 吗,很明显的错误。
  • 这行得通,但你能解释一下为什么吗? AFAICT 模块是 es6。为什么还要设置节点?

标签: javascript typescript


【解决方案1】:

正如 cmets 中所发布的,我需要将 "moduleResolution": "node" 添加到我的 tsconfig.json 中。不知道为什么,因为我所做的一切都与 Node.js 无关。但这确实奏效了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2016-03-12
    • 2018-10-27
    • 2020-11-22
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    相关资源
    最近更新 更多