【问题标题】:Import/Require nodejs modules without @types in Typescript in 20182018 年在 Typescript 中导入/要求没有 @types 的 nodejs 模块
【发布时间】:2018-06-21 19:59:44
【问题描述】:

我有一个用于网站的 typescript nodejs 项目。我需要使用这个特定 nodejs 模块中可用的功能:https://www.npmjs.com/package/weather-js

此模块的存储库中没有可用的 .d.ts 文件,“@types”打字稿存储库中也没有可用的文件。我不需要此模块的类型定义,但 typescript 不包含它并产生错误。

无论我尝试哪种方式导入,我都会得到

TS2304: Cannot find name 'require'.

在构建控制台中,或

TypeError: qs.escape is not a function

在浏览器开发控制台中。

StackOverflow 上的许多回复提出了需要 2018 年不再可用的存储库的解决方案,或者可能有效但对我来说仍然会产生错误的解决方案

TypeError: qs.escape is not a function

2018 年在 typescript 中使用/import/require/consume nodejs 模块功能(没有可用的 .d.ts 定义)的正确方法是什么?

【问题讨论】:

    标签: javascript node.js typescript import require


    【解决方案1】:

    您可以添加一个虚拟定义以允许它导入,但无需实际输入模块内容(尽管如果您应该完全输入它们并提交给DefinitlyTyped,这样每个人都可以从类型安全中受益!)

    天气-js.d.ts

    // declaring module will allow typescript to import the module
    declare module 'weather-js' {
      // typing module default export as `any` will allow you to access its members without compiler warning
      var weatherJs: any; 
      export default weatherJs;
    }
    

    你的代码.ts

    import weather from 'weather-js'
    
    weather.find({search: 'San Francisco, CA', degreeType: 'F'}, () => {})
    

    【讨论】:

    • 我在与 yourCode.ts 相同的文件中创建了 weather-js.d.ts 文件。项目编译,但浏览器控制台显示“TypeError: Cannot read property 'find' of undefined”
    • 如果你在同一个文件中添加模块定义,它会编译很奇怪,因为它会变成模块扩充,但是没有现有的模块可以扩充,所以你应该得到编译器错误Invalid module name in augmentation. Module 'weather-js' resolves to an untyped module跨度>
    猜你喜欢
    • 2012-10-09
    • 2021-11-28
    • 2018-07-23
    • 2023-03-09
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多