/* * This script generates an index file for each asset folder specified in `assetFolders`. * The index file will export all assets in the folder as an object. * * Usage: * 1. Add the names of your asset folders to the `assetFolders` array. * 2. Run `pnpm assets gen` to generate the index files. * * The generated index files will have the name `index.ts` and will be located in the root of each asset folder. */ import fs from 'fs'; import { dirname, join } from 'path'; import prettier from 'prettier'; import { fileURLToPath } from 'url'; const assetFolders = ['icons', 'images']; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); assetFolders.forEach((folder) => { const indexFilePath = join(__dirname, '..', folder, 'index.ts'); const assetsFolderPath = join(__dirname, '..', folder); // Delete the index file if it already exists. if (fs.existsSync(indexFilePath)) { fs.unlinkSync(indexFilePath); } const fileNames = fs.readdirSync(assetsFolderPath); // Generate the import statements for each asset. const assetImports = fileNames .filter((fileName) => fileName !== 'index.ts') .map((fileName) => { const variableName = fileName.split('.')[0].replace(/-/g, ''); return `import ${variableName} from './${fileName}';`; }) .join('\n'); // Generate the export statements for each asset. const assetExports = fileNames .filter((fileName) => fileName !== 'index.ts') .map((fileName) => { const variableName = fileName.split('.')[0].replace(/-/g, ''); return `${variableName},`; }) .join('\n'); // Generate the index file content. const indexFileContent = ` /* * This file was automatically generated by a script. * To regenerate this file, run: pnpm assets gen */ ${assetImports}\n\nexport {\n ${assetExports}\n};\n`; // Write the index file. prettier.resolveConfig(join(__dirname, '..', '..', '..', '.prettierrc.js')).then((options) => { fs.writeFileSync( indexFilePath, prettier.format(indexFileContent, { ...options, parser: 'typescript' }) ); }); });