ts-typedfiles
Version:
Generate filepaths from directory structure
38 lines (37 loc) • 1.06 kB
JavaScript
// src/parser.ts
import * as fs from "fs";
import * as path from "path";
function generateFilePathsType(directoryPath, outputFilePath, typeName) {
const filePaths = [];
function readFiles(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
readFiles(filePath);
} else if (stat.isFile()) {
filePaths.push(filePath);
}
}
}
try {
readFiles(directoryPath);
const typeDefinition = `
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT EDIT.
export type ${typeName} =
${filePaths.map((filePath) => `"${filePath}"`).join(" |\n ")};
`;
fs.writeFileSync(outputFilePath, typeDefinition, {
flag: "w"
});
console.info(
`\u2705 Successfully generated type definition file: ${outputFilePath}`
);
} catch (error) {
console.error("\u274C Error generating type definition:", error.message);
}
}
export {
generateFilePathsType
};