NodeJS如何在TypeScript文件中要求? [英] How to NodeJS require inside TypeScript file?

查看:63
本文介绍了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天全站免登陆