generator.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // const fs = require('fs');
  2. // const path = require('path');
  3. import * as path from 'path'
  4. import * as fs from 'fs';
  5. import { log } from 'console';
  6. // 选定assets文件夹路径
  7. const assetsPath = 'assets';
  8. // 选定ts文件夹路径
  9. const tsPath = './libs';
  10. // 生成ts文件路径
  11. const tsAssetsPath = path.join(tsPath, assetsPath);
  12. // 读取assets文件夹下的所有文件
  13. fs.readdir(assetsPath, (err, files) => {
  14. if (err) {
  15. console.error(err);
  16. return;
  17. }
  18. // 遍历每个文件
  19. files.forEach((file) => {
  20. const filePath = path.join(assetsPath, file);
  21. const stat = fs.statSync(filePath);
  22. if (stat.isDirectory()) {
  23. console.log(`dir: ${filePath}`);
  24. } else if (stat.isFile()) {
  25. // console.log(`file: ${filePath}`);
  26. // 生成ts文件名称和内容
  27. const fileName = path.basename(file, path.extname(file)).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
  28. const tsFileName = fileName + '.ts';
  29. const tsFilePath = path.join(tsAssetsPath, tsFileName);
  30. console.log()
  31. console.log('tsName:' + tsFileName)
  32. // console.log('tsFilePath:' + tsFilePath)
  33. let tsFileContent = `import ${fileName} from '../../assets/${path.basename(file).toString()}' \n export default ${fileName}`;
  34. // try {
  35. // // 读取assets文件的内容
  36. // const fileContent = fs.readFileSync(filePath, 'utf8');
  37. // if (fileContent.includes('<svg')) {
  38. // // svg文件内容
  39. // const match = fileContent.match(/<svg[^>]*>(.*?)<\/svg>/s);
  40. // if (match) {
  41. // tsFileContent += `import icon${path.basename(file, path.extname(file))} from './assets/${file}';\n`;
  42. // tsFileContent += `export default ${match[1].trim()};\n\n`;
  43. // }
  44. // } else if (fileContent.includes('.png')) {
  45. // // png文件内容
  46. // const match = fileContent.match(/data:image\/png;,\s*base64\((.*?)\)/);
  47. // if (match) {
  48. // tsFileContent += `import icon${path.basename(file, path.extname(file))} from './assets/${file}';\n`;
  49. // tsFileContent += `export default ${match[1].trim()};\n\n`;
  50. // }
  51. // }
  52. // } catch (error) {
  53. // console.error(error);
  54. // return;
  55. // }
  56. // 写入ts文件
  57. fs.writeFileSync(tsFilePath, tsFileContent);
  58. console.log(`ts file ${tsFileName} created!`);
  59. }
  60. });
  61. });