ads-icons-react
Version:
ADS icons for React usage
64 lines (53 loc) • 2.31 kB
JavaScript
const fs = require("fs").promises;
const path = require("path");
const templateReact = require("./react-template");
const { createComponentName } = require("../utils/tools");
/**
* Asynchronously generates React component files for a given array of icons. Each icon's data
* is used to create a React component file and an index.js file for exports. It also aggregates
* all component import statements into a single 'icons.js' file.
*
* @async
* @param {Array<{file: string, data: string}>} icons - An array of objects representing icons,
* each containing the 'file' name and the 'data' as a UTF-8 string.
* @throws {Error} Throws an error if there is an issue creating directories, writing files,
* or during any part of the file generation process.
* @returns {Promise<void>} A promise that resolves when all React components have been successfully
* generated and import statements have been aggregated and written to 'icons.js'.
*/
const generateReactComponent = async (icons) => {
try {
// Aggregate import statements
let importStatements = "";
for (const icon of icons) {
if (!icon.file) {
continue;
}
const parsedName = createComponentName(icon.file);
importStatements += `export { ${parsedName} } from './${parsedName}';\n`;
const dataReact = templateReact(icon);
const dataIndex = `import ${parsedName} from './${parsedName}';
export { ${parsedName} };`;
const componentDir = path.join(
process.cwd(),
`${path.relative(process.cwd(), "src/components")}/${parsedName}`
);
await fs.mkdir(componentDir, { recursive: true });
const writePath = path.join(componentDir, `${parsedName}.tsx`);
const writePathIndex = path.join(componentDir, "index.ts");
await fs.writeFile(writePath, dataReact, "utf8");
await fs.writeFile(writePathIndex, dataIndex, "utf8");
}
// Write aggregated import statements to icons.js
const writeIndex = path.join(
process.cwd(),
path.relative(process.cwd(), "src/components"),
"index.ts"
);
await fs.appendFile(writeIndex, importStatements, "utf8");
} catch (err) {
console.error(`✗ ERROR : ${err}`);
throw err; // Rethrow or handle error as needed
}
};
module.exports = generateReactComponent;