How to import node module in Typescript without type definitions?

前端 未结 4 1281
[愿得一人]
[愿得一人] 2021-02-20 12:16

When I try to import node.js module in Typescript like this:

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

without providing type definit

相关标签:
4条回答
  • 2021-02-20 12:40

    The trick is to use purely JavaScript notation:

    const co = require('co');
    
    0 讨论(0)
  • 2021-02-20 12:41

    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 rework the stub .d.ts file slightly:

    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 lowers the barrier to writing out real declarations as you need them.

    0 讨论(0)
  • 2021-02-20 12:47

    Your options are to either import it outside TypeScript's module system (by calling a module API like RequireJS or Node directly by hand) so that it doesn't try to validate it, or to add a type definition so that you can use the module system and have it validate correctly. You can stub the type definition though, so this can be very low effort.

    Using Node (CommonJS) imports directly:

    // Note there's 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
    });
    

    Be aware that in either of these cases this may mix weirdly with using real normal TypeScript module imports in the same file (you can end up with two layers of module definition, especially on the RequireJS side, as TypeScript tries to manage modules you're also managing by hand). I'd recommend either using just this approach, or using real type definitions.

    Stubbing type definitions:

    Getting proper type definitions would be best, and if those are available or you have time to write them yourself you should definitely should.

    If not though, you can just give your whole module the any type, and put your module into the module system without having to actually type it:

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

    This should allow you to import module-name and have TypeScript know what you're talking about. You'll still need to ensure that importing module-name does actually load it successfully at runtime with whatever module system you're using, or it will compile but then fail to actually run.

    0 讨论(0)
  • 2021-02-20 12:51

    Just import the module the following way:

    import 'co';
    
    0 讨论(0)
提交回复
热议问题