如何从 TypeScript 的目录中导入所有模块? [英] How to import all modules from a directory in TypeScript?

查看:105
本文介绍了如何从 TypeScript 的目录中导入所有模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TypeScript 手册中描述了一些导入模块的技术:

In TypeScript handbook few techniques for importing modules are described:

  • 从模块导入单个导出: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?

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

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

推荐答案

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

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

示例:

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

a.ts

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

b.ts

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

index.ts

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

您可以使用 * 字符以一行重新导出模块的每个导出.请注意,如果已导出同名成员,TypeScript 会出错(感谢@haysclark 提供提示).

You can use the * character to re-export every export of a module with a single line. Be aware that TypeScript will error if a member with the same name has already been exported though (thanks to @haysclark for the tip).

export * from "./somePath";

索引名可以去掉(和javascript一样):

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

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

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

这篇关于如何从 TypeScript 的目录中导入所有模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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