UNPKG

@tsed/barrels

Version:

A simple tool to generate barrels for your TypeScript project

46 lines (35 loc) 1.45 kB
import {writeFile} from "node:fs/promises"; import path, {dirname, join} from "node:path"; import {join as joinPosix} from "node:path/posix"; import {globby} from "globby"; async function generateIndex(directory, {cwd, excluded, noSemicolon}) { const baseIndex = join(cwd, directory?.path ?? directory); const files = await globby(["**/*.{ts,tsx}", "!index.{ts,tsx}", ...excluded], { cwd: path.join(cwd, directory) }); const exports = files .sort((a, b) => a.localeCompare(b)) .map((file) => { // TODO set .js after all configuration are ok to resolve .js return `export * from "./${file.replace(".ts", ".js")}"${noSemicolon ? "" : ";"}`; }); const content = ["/**", " * @file Automatically generated by @tsed/barrels.", " */", ...exports]; await writeFile(join(baseIndex, "index.ts"), content.join("\n") + "\n", {encoding: "utf8"}); } export async function generateBarrels({exclude, directory, cwd, noSemicolon}) { const excluded = exclude.map((path) => `!${path}`).concat(directory.map((path) => `!${path}/index.ts`)); const directories = ( await globby( directory.map((d) => { return joinPosix(d, "*"); }), { cwd } ) ).reduce((set, file) => { return set.add(dirname(file)); }, new Set()); const promises = [...directories.keys()].map((directory) => generateIndex(directory, {excluded, cwd, noSemicolon})); await Promise.all(promises); }