问题描述
如何从TypeScript
类中加载常规的NodeJS模块(从node_modules
开始)?
How do I load a regular NodeJS module (from node_modules
) from within a TypeScript
class?
当我尝试编译包含以下内容的.ts
文件时:
When I try to compile .ts
file that contains:
var sampleModule = require('modulename');
在此范围内,编译器提示我无法使用require. (该行位于文件的开头).
Compiler prompts that I can't use require in this scope. (that line is at the beginning of the file).
推荐答案
当无法找到符号时,Typescript总是会抱怨.编译器随附了window
,document
的一组默认定义,并在名为lib.d.ts
的文件中指定了这些默认定义.如果我在此文件中为require
做grep,则找不到函数require
的定义.因此,我们必须自己告诉编译器该函数将在运行时使用declare
语法存在:
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.
这篇关于nodejs需要在TypeScript文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!