icon.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. const fs = require("fs");
  2. const path = require("path");
  3. const AdmZip = require("adm-zip");
  4. // 清理所有临时文件
  5. function cleanupTempDir() {
  6. const tempDir = path.join(".cool", "temp");
  7. if (fs.existsSync(tempDir)) {
  8. try {
  9. fs.rmSync(tempDir, { recursive: true, force: true });
  10. } catch (error) {
  11. console.warn(`❌ 清理临时目录失败: ${tempDir}`, error);
  12. }
  13. }
  14. }
  15. // 确保临时目录存在
  16. function ensureTempDir() {
  17. const tempDir = path.join(".cool", "temp");
  18. if (!fs.existsSync(tempDir)) {
  19. fs.mkdirSync(tempDir, { recursive: true });
  20. }
  21. }
  22. // 创建icons目录和子目录
  23. function ensureDistDir(folderName = "") {
  24. const iconsPath = folderName ? path.join("icons", folderName) : "icons";
  25. if (!fs.existsSync(iconsPath)) {
  26. fs.mkdirSync(iconsPath, { recursive: true });
  27. }
  28. }
  29. // 读取zip文件列表
  30. function getZipFiles() {
  31. const iconsDir = path.join(".cool", "icons");
  32. if (!fs.existsSync(iconsDir)) {
  33. console.error(`❌ 目录不存在: ${iconsDir}`);
  34. return [];
  35. }
  36. return fs.readdirSync(iconsDir).filter((item) => {
  37. const filePath = path.join(iconsDir, item);
  38. const stats = fs.statSync(filePath);
  39. return stats.isFile() && item.endsWith(".zip");
  40. });
  41. }
  42. // 解压zip文件到临时目录
  43. function extractZipFile(zipPath, folderName) {
  44. try {
  45. const zip = new AdmZip(zipPath);
  46. const tempDir = path.join(".cool", "temp", folderName);
  47. // 确保临时目录存在
  48. if (!fs.existsSync(tempDir)) {
  49. fs.mkdirSync(tempDir, { recursive: true });
  50. }
  51. // 解压到临时目录
  52. zip.extractAllTo(tempDir, true);
  53. // 检查是否有额外的顶层文件夹
  54. const extractedItems = fs.readdirSync(tempDir);
  55. // 如果只有一个项目且是文件夹,则可能是额外的包装文件夹
  56. if (extractedItems.length === 1) {
  57. const singleItem = extractedItems[0];
  58. const singleItemPath = path.join(tempDir, singleItem);
  59. const stats = fs.statSync(singleItemPath);
  60. if (stats.isDirectory()) {
  61. // 检查这个文件夹是否包含我们需要的文件
  62. const innerItems = fs.readdirSync(singleItemPath);
  63. const hasIconFiles = innerItems.some(
  64. (item) =>
  65. item.endsWith(".ttf") || item.endsWith(".json") || item.endsWith(".css")
  66. );
  67. if (hasIconFiles) {
  68. return singleItemPath;
  69. }
  70. }
  71. }
  72. return tempDir;
  73. } catch (error) {
  74. console.error(`❌ 解压失败: ${zipPath}`, error);
  75. return null;
  76. }
  77. }
  78. // 将TTF文件转换为base64
  79. function ttfToBase64(ttfPath) {
  80. try {
  81. const ttfBuffer = fs.readFileSync(ttfPath);
  82. return ttfBuffer.toString("base64");
  83. } catch (error) {
  84. console.error(`❌ 读取TTF文件失败: ${ttfPath}`, error);
  85. return null;
  86. }
  87. }
  88. // 生成TypeScript文件
  89. function generateTypeScript(folderName, iconData) {
  90. const tsContent = `export const ${folderName} = {\n${iconData
  91. .map((item) => `\t"${item.name}": "${item.unicode}"`)
  92. .join(",\n")}\n};\n`;
  93. const outputPath = path.join("icons", folderName, "index.ts");
  94. fs.writeFileSync(outputPath, tsContent);
  95. }
  96. // 生成SCSS文件
  97. function generateSCSS(folderName, base64Data) {
  98. const scssContent = `@font-face {\n\tfont-family: "${folderName}";\n\tsrc: url("data:font/ttf;base64,${base64Data}") format("woff");\n}\n`;
  99. const outputPath = path.join("icons", folderName, "index.scss");
  100. fs.writeFileSync(outputPath, scssContent);
  101. }
  102. // 从CSS文件提取图标数据(用于remixicon等)
  103. function extractIconsFromCSS(cssPath) {
  104. try {
  105. const cssContent = fs.readFileSync(cssPath, "utf8");
  106. const iconData = [];
  107. // 匹配CSS中的图标规则,例如:.ri-home-line:before { content: "\ee2b"; }
  108. const regex = /\.ri-([^:]+):before\s*{\s*content:\s*"\\([^"]+)"/g;
  109. let match;
  110. while ((match = regex.exec(cssContent)) !== null) {
  111. const iconName = match[1];
  112. const unicode = match[2];
  113. iconData.push({
  114. name: iconName,
  115. unicode: unicode
  116. });
  117. }
  118. return iconData;
  119. } catch (error) {
  120. console.error(`❌ 读取CSS文件失败: ${cssPath}`, error);
  121. return [];
  122. }
  123. }
  124. // 读取和处理图标数据
  125. function processIconData(jsonPath) {
  126. try {
  127. const jsonData = JSON.parse(fs.readFileSync(jsonPath, "utf8"));
  128. return jsonData.glyphs.map((item) => ({
  129. name: item.font_class,
  130. unicode: item.unicode
  131. }));
  132. } catch (error) {
  133. console.error(`❌ 读取JSON文件失败: ${jsonPath}`, error);
  134. return [];
  135. }
  136. }
  137. // 处理单个zip文件
  138. function processZipFile(zipFileName) {
  139. const folderName = path.basename(zipFileName, ".zip");
  140. const zipPath = path.join(".cool", "icons", zipFileName);
  141. // 解压zip文件
  142. const tempDir = extractZipFile(zipPath, folderName);
  143. if (!tempDir) {
  144. return null;
  145. }
  146. // 图标库名称
  147. const ptName = ["iconfont", "remixicon"];
  148. // 获取文件路径
  149. const getFilePath = (ext) => {
  150. let filePath = null;
  151. for (const name of ptName) {
  152. const tempPath = path.join(tempDir, `${name}.${ext}`);
  153. if (fs.existsSync(tempPath)) {
  154. filePath = tempPath;
  155. break;
  156. }
  157. }
  158. return filePath;
  159. };
  160. // 在解压后的目录中查找文件
  161. const jsonPath = getFilePath("json");
  162. const cssPath = getFilePath("css");
  163. const ttfPath = getFilePath("ttf");
  164. if (!ttfPath) {
  165. console.warn(`⚠️跳过 ${folderName}: 缺少 TTF 文件`);
  166. return null;
  167. }
  168. let iconData = [];
  169. // 优先使用JSON文件
  170. if (jsonPath) {
  171. iconData = processIconData(jsonPath);
  172. }
  173. // 如果没有则尝试CSS文件
  174. else if (cssPath) {
  175. iconData = extractIconsFromCSS(cssPath);
  176. } else {
  177. console.warn(`⚠️ 跳过 ${folderName}: 缺少 ${jsonPath} 或 ${cssPath}`);
  178. return null;
  179. }
  180. if (iconData.length === 0) {
  181. console.warn(`⚠️ ${folderName}: 没有找到图标数据`);
  182. return null;
  183. }
  184. console.log(`✅ ${zipFileName} 找到 ${iconData.length} 个图标`);
  185. // 转换TTF为base64
  186. const base64Data = ttfToBase64(ttfPath);
  187. if (!base64Data) {
  188. console.error(`❌ ${folderName}: TTF转换失败`);
  189. return null;
  190. }
  191. // 为该文件夹创建icons子目录
  192. ensureDistDir(folderName);
  193. // 生成TypeScript文件
  194. generateTypeScript(folderName, iconData);
  195. // 生成SCSS文件
  196. generateSCSS(folderName, base64Data);
  197. return folderName;
  198. }
  199. // 生成主index.ts文件
  200. function generateIndexTS(processedFolders) {
  201. const imports = processedFolders
  202. .map((folder) => `import { ${folder} } from "./${folder}";`)
  203. .join("\n");
  204. const exports = `export const icons = {\n${processedFolders
  205. .map((folder) => `\t${folder}`)
  206. .join(",\n")}\n};\n`;
  207. const content = `${imports}\n\n${exports}`;
  208. fs.writeFileSync("icons/index.ts", content);
  209. }
  210. // 生成主index.scss文件
  211. function generateIndexSCSS(processedFolders) {
  212. const imports = processedFolders
  213. .map((folder) => `@import "./${folder}/index.scss";`)
  214. .join("\n");
  215. fs.writeFileSync("icons/index.scss", imports + "\n");
  216. }
  217. // 扫描icons目录下的实际文件夹
  218. function getActualIconFolders() {
  219. const iconsDir = "icons";
  220. if (!fs.existsSync(iconsDir)) {
  221. return [];
  222. }
  223. return fs.readdirSync(iconsDir).filter((item) => {
  224. const itemPath = path.join(iconsDir, item);
  225. const stats = fs.statSync(itemPath);
  226. return stats.isDirectory();
  227. });
  228. }
  229. // 主函数
  230. function main() {
  231. console.log("🚀 开始处理字体文件...\n");
  232. // 确保临时目录存在
  233. ensureTempDir();
  234. // 确保icons目录存在
  235. ensureDistDir();
  236. try {
  237. // 获取所有zip文件
  238. const zipFiles = getZipFiles();
  239. // 处理每个zip文件
  240. const processedFolders = [];
  241. for (const zipFile of zipFiles) {
  242. const result = processZipFile(zipFile);
  243. if (result) {
  244. processedFolders.push(result);
  245. }
  246. }
  247. // 扫描icons目录下的实际文件夹
  248. const actualFolders = getActualIconFolders();
  249. if (actualFolders.length > 0) {
  250. // 生成主index文件
  251. generateIndexTS(actualFolders);
  252. generateIndexSCSS(actualFolders);
  253. }
  254. if (processedFolders.length > 0) {
  255. console.log(
  256. `\n🎉 成功处理了 ${processedFolders.length} 个字体包: ${processedFolders.join(", ")}`
  257. );
  258. }
  259. } catch (error) {
  260. console.error("❌ 脚本执行出错:", error);
  261. } finally {
  262. cleanupTempDir();
  263. }
  264. }
  265. // 运行脚本
  266. if (require.main === module) {
  267. main();
  268. }