How to import node module in Typescript without type definition?

When I try to import the node.js module into Typescript as follows:

import co = require('co'); import co from 'co'; 

without providing type definitions, both lines report the same error:

 error TS2307: Cannot find module 'co'. 

How to import it?

+8
source share
3 answers

The trick is to use pure JavaScript notation:

 const co = require('co'); 
+3
source

Your parameters must either import it outside the TypeScript module system (by directly calling the module API module, for example RequireJS or Node) so that it does not try to check it, or add a type definition so that you can use the module system and check it correctly. You can drown out the type definition, although this can be a very low effort.

Using Node Import (CommonJS) directly:

 // Note there no 'import' statement here. var loadedModule: any = require('module-name'); // Now use your module however you'd like. 

Using RequireJS directly:

 define(["module-name"], function (loadedModule: any) { // Use loadedModule however you'd like }); 

Keep in mind that in any of these cases, this can strangely mix using real normal import of TypeScript modules in the same file (you can get two levels of module definition, especially on the RequireJS side, as TypeScript tries to manage modules that you also manage manually ) I would recommend using this approach or using real type definitions.

Stubbing type definitions:

Getting the right type definitions would be best, and if they are available or you have time to write them yourself, you definitely need to.

If this is not the case, you can simply tell the entire module the type any and put your module in the module system without typing it:

 declare module 'module-name' { export = <any> {}; } 

This should allow you to import the module-name and have TypeScript know what you are talking about. You still need to make sure that importing the module name really loads it at run time using any used module system, or it will be compiled, but then it won’t complete.

+8
source

I got an error when I used the "Stubbing Type Definitions" approach in Tim Perry's answer: error TS2497: Module ''module-name'' resolves to a non-module entity and cannot be imported using this construct.

The solution was to process the .d.ts stub file a .d.ts :

 declare module 'module-name' { const x: any; export = x; } 

And then you can import via:

 import * as moduleName from 'module-name'; 

Creating your own stub file reduces the barrier to writing real ads as needed.

+3
source

All Articles