nodejs需要在TypeScript文件中 [英] nodejs require inside TypeScript file

查看:109
本文介绍了nodejs需要在TypeScript文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从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总是会抱怨.编译器随附了windowdocument的一组默认定义,并在名为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文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆