在2018年在Typescript中导入/需要不带@types的Node.js模块 [英] Import/Require nodejs modules without @types in Typescript in 2018

查看:394
本文介绍了在2018年在Typescript中导入/需要不带@types的Node.js模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a typescript nodejs project for a website. I need to use functionality that is available in this specific nodejs module: https://www.npmjs.com/package/weather-js

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

This module does not have a .d.ts file available in its repository, nor is there one available in the '@types' typescript repository. I do not require type definitions for this module, but typescript does not include it and produces errors.

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

No matter which way I try to import, I either get

TS2304: Cannot find name 'require'.

在构建控制台中,或

TypeError: qs.escape is not a function

在浏览器开发者控制台中.

in the browser dev console.

StackOverflow上的许多答复都提出了一些解决方案,这些解决方案要求存储库在2018年不再可用,或者可能会起作用,但对我来说仍然会产生错误

Many responses here on StackOverflow suggest solutions that require repositories that are no longer available in 2018, or that might work but for me still produce the error

TypeError: qs.escape is not a function

在2018年的打字稿中使用/导入/要求/消费Node.js模块功能(没有可用的.d.ts定义)的正确方法是什么?

推荐答案

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

You can add a dummy definition to allow it to import but without actually typing the module contents (although maybe if you should type them fully and submit to DefinitlyTyped so the everyone can benefit from type safety too!)

weather-js.d.ts

weather-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;
}

yourCode.ts

yourCode.ts

import weather from 'weather-js'

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

这篇关于在2018年在Typescript中导入/需要不带@types的Node.js模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆