如何从 TypeScript 的目录中导入所有模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40702842/
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-09 07:28:56  来源:igfitidea点击:

How to import all modules from a directory in TypeScript?

typescript

提问by Landeeyo

In TypeScript handbookfew techniques for importing modules are described:

在 TypeScript手册中,介绍了一些导入模块的技术:

  • Import a single export from a module: import { ZipCodeValidator } from "./ZipCodeValidator";
  • Import a single export from a module and rename it: import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
  • Import entire module: import * as validator from "./ZipCodeValidator";
  • 从模块导入单个导出: import { ZipCodeValidator } from "./ZipCodeValidator";
  • 从模块导入单个导出并重命名: import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
  • 导入整个模块: import * as validator from "./ZipCodeValidator";

I expect there's one more option but nowhere I can find it. Is it possible to import all modules from a given directory?

我希望还有一种选择,但我无处可寻。是否可以从给定目录导入所有模块?

I guess the syntax should be more or less like this: import * from "./Converters".

我想语法应该或多或少是这样的:import * from "./Converters".

回答by marvinhagemeister

No this is not possible. What most people do is create an index.jsfile which re-exports all files in the same directory.

不,这是不可能的。大多数人所做的是创建一个index.js文件,该文件将同一目录中的所有文件重新导出。

Example:

例子:

my-module/
  a.ts
  b.ts
  index.ts

a.ts

a.ts

export default function hello() {
  console.log("hello");
}

b.ts

b.ts

export default function world() {
  console.log("world");
}

index.ts

索引.ts

export { default as A } from "./a";
export { default as B } from "./b";

The index name can be dropped (same as in javascript):

可以删除索引名称(与在 javascript 中相同):

import * as whatever from "./my-module";

console.log(whatever);
// Logs: { A: [Function: hello], B: [Function: world] }