我正在使用 Angular 14 并构建一个共享库。我有这个项目结构
+ projects
+ my-lib
- package.json
+ src
- public-api.ts
+ lib
+ helpers
- index.ts
- my-first-helper.ts
- my-second-helper.ts
...
在“public_api.ts”中我有
export * from './lib/helpers';
在 helpers/index.ts 中我有
export * from './my-first-helper';
export * from './my-second-helper';
我的问题是,每次我将新文件添加到“helpers”目录时,我都必须编辑我的“index.ts”以明确包含它。有没有一种方法可以编写我的“index.ts”文件来导出“helpers”目录中每个文件中的所有内容?
记住 Typescript 只是一种超集语言。编译后它将是 Javascript,Javascript 需要一个entry point 用于所有需要由 Node.js 解释的模块。 Node在编译时首先会查找package.json,如果没有找到,会默认查找index.js。
一个模块可以是一个或多个文件,Node.js 不需要知道你的软件内部结构,Node 只需要知道模块上的导入(使用 require 关键字)。
你可以自动化这个过程。可以创建一个脚本,在添加文件或从目录中删除文件时始终管理您的 index.ts。或者使用库,比如 (create-ts-index)
您可以使用 Node.js 文件系统模块动态导出 helpers 目录中的所有模块,而无需显式列出每个模块。这是一个如何修改 helpers/index.ts 文件的示例:
import * as fs from 'fs';
import * as path from 'path';
const files = fs.readdirSync(__dirname);
for (const file of files) {
const ext = path.extname(file);
if (ext === '.ts' && file !== 'index.ts') {
const moduleName = path.basename(file, ext);
export * from `./${moduleName}`;
}
}