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?
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 .
You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel.
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.
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.
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'}, () => {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With