如何使用 TypeScript 导入外部文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12699940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:11:20  来源:igfitidea点击:

How can I import an external file with TypeScript?

typescript

提问by Peter Olson

I have a node app that has a string of requires, like this:

我有一个包含requires字符串的节点应用程序,如下所示:

var express = require('express'),
    router = require('./router'),
    data = require('./data');

This code works without changes, but how can I take full advantage of TypeScript modules? Just using

此代码无需更改即可运行,但我如何才能充分利用 TypeScript 模块?只是使用

import data = module("./data")

will tell me

会告诉我

The name ''./data'' does not exist in the current scope

当前作用域中不存在名称“./data”

How can I import an external file with TypeScript?

如何使用 TypeScript 导入外部文件?

采纳答案by chuckj

The example,

这个例子,

http://www.typescriptlang.org/Samples/#ImageBoard

http://www.typescriptlang.org/Samples/#ImageBoard

contains a file called node.d.tswhich shows how to declare the types for an existing node.js module.

包含一个名为的文件node.d.ts,该文件显示了如何声明现有 node.js 模块的类型。

TypeScript requires the module be declared for you use to importsyntax. This is typically provided in a .d.tsfile but can be included in the same file. An example this might look like,

TypeScript 需要声明模块以供您使用import语法。这通常在.d.ts文件中提供,但可以包含在同一文件中。这可能是一个例子,

declare module "./data" {
    function getData(): number;
}

import data = module("./data");

var myData = data.getData();

In a .d.tsfile the declarekeywords is implied and can be omitted.

.d.ts文件中,declare关键字是隐含的,可以省略。