【问题标题】:Import native node modules correctly in Typescript在 Typescript 中正确导入本机节点模块
【发布时间】:2018-07-04 10:38:52
【问题描述】:

我已经使用 node 很长一段时间了(用于我的后端)和带有 ionic 的 typescript(用于前端)。在 Ionic 上,我意识到仅仅因为 TypeScript,我已经设法避免了许多陷阱和错误。因此,我决定将我所有的纯 JS 后端转换为 TypeScript。

我遇到的第一个障碍是如何正确导入 httposchild_process 等原生节点模块。

在大多数模块上,您通常可以执行import { some_export } from 'that_module' 之类的操作。我还可以在 @types/ 存储库中查看节点的类型定义。我试过import { http, os } from 'node',但我收到了投诉

/node_modules/@types/node/index.d.ts 不是模块

因此我的问题是我应该如何导入本机节点模块?

【问题讨论】:

    标签: node.js typescript import native


    【解决方案1】:

    感谢this simple tutorial的一些简单阅读,我已经设法解决了这个问题

    据我了解,本机模块是独立模块,没有在 node 下命名空间。因此,您应该直接从它们导入。

    只需这样做:

    import * as http from "http";
    import * as os from "os";
    import * as path from "path";
    .
    .
    .
    and so on
    

    【讨论】:

    • 还有一件事 - 你需要告诉 typescript 编译器这些来自哪里 - 它是在 tsconfig.json 中完成的,使用以下行:“compilerOptions”:{“types”:[ “节点”] }
    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 2013-08-25
    • 2017-04-03
    • 1970-01-01
    • 2018-08-02
    • 2017-11-17
    • 2018-06-10
    相关资源
    最近更新 更多