nodejs require inside TypeScript file

前端 未结 4 1787
佛祖请我去吃肉
佛祖请我去吃肉 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: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.

提交回复
热议问题