nodejs require inside TypeScript file

前端 未结 4 1785
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 18:23

How do I load a regular NodeJS module (from node_modules) from within a TypeScript class?

When I try to compile .ts file that

相关标签:
4条回答
  • 2020-11-29 18:25

    Use typings to access node functions from TypeScript:

    typings install env~node --global
    

    If you don't have typings

    0 讨论(0)
  • 2020-11-29 18:27

    Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window, document and such specified in a file called lib.d.ts. If I do a grep for require in this file I can find no definition of a function require. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare syntax:

    declare function require(name:string);
    var sampleModule = require('modulename');
    

    On my system, this compiles just fine.

    0 讨论(0)
  • 2020-11-29 18:40

    The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require(). This was previously done using packages like typings, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:

    npm install --save-dev @types/node
    

    Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.

    0 讨论(0)
  • 2020-11-29 18:45

    The correct syntax is:

    import sampleModule = require('modulename');
    

    or

    import * as sampleModule from 'modulename';
    

    Then compile your TypeScript with --module commonjs.

    If the package doesn't come with an index.d.ts file and its package.json doesn't have a "typings" property, tsc will bark that it doesn't know what 'modulename' refers to. For this purpose you need to find a .d.ts file for it on http://definitelytyped.org/, or write one yourself.

    If you are writing code for Node.js you will also want the node.d.ts file from http://definitelytyped.org/.

    0 讨论(0)
提交回复
热议问题