Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import/Require nodejs modules without @types in Typescript in 2018

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

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'.

in the build console, or

TypeError: qs.escape is not a function

in the browser dev console.

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

What is the correct way to use/import/require/consume nodejs module functionality (without .d.ts definitions available) in typescript in 2018?

like image 712
Marvos Avatar asked Jan 12 '18 10:01

Marvos


People also ask

Why does Nodejs use require instead of import?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with .

Can we use import instead of require in node JS?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel.

Should I use import or require in Nodejs?

NOTE: You must note that you can't use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program.

What is the difference between import and require in TypeScript?

Require is more of dynamic analysis, and import is more of static analysis. Require Throws error at runtime and Import throws error while parsing. Require is Nonlexical and Import is Lexical.


1 Answers

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

// 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

import weather from 'weather-js'

weather.find({search: 'San Francisco, CA', degreeType: 'F'}, () => {})
like image 170
alechill Avatar answered Nov 15 '22 14:11

alechill