icon.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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(originalFolderName, camelCaseName, iconData) {
  90. const tsContent = `export const ${camelCaseName} = {\n${iconData
  91. .map((item) => `\t"${item.name}": "${item.unicode}"`)
  92. .join(",\n")}\n};\n`;
  93. const outputPath = path.join("icons", originalFolderName, "index.ts");
  94. fs.writeFileSync(outputPath, tsContent);
  95. }
  96. // 生成SCSS文件
  97. function generateSCSS(originalFolderName, base64Data) {
  98. const scssContent = `@font-face {\n\tfont-family: "${toCamelCase(originalFolderName)}";\n\tsrc: url("data:font/ttf;base64,${base64Data}") format("woff");\n}\n`;
  99. const outputPath = path.join("icons", originalFolderName, "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. // 将连字符转换为驼峰命名的函数
  138. function toCamelCase(str) {
  139. return str.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
  140. }
  141. // 处理单个zip文件
  142. function processZipFile(zipFileName) {
  143. const originalFolderName = path.basename(zipFileName, ".zip");
  144. const folderName = toCamelCase(originalFolderName); // 转换为驼峰命名用于变量名
  145. const zipPath = path.join(".cool", "icons", zipFileName);
  146. // 解压zip文件 (使用原始文件夹名称)
  147. const tempDir = extractZipFile(zipPath, originalFolderName);
  148. if (!tempDir) {
  149. return null;
  150. }
  151. // 图标库名称
  152. const ptName = ["iconfont", "remixicon"];
  153. // 获取文件路径
  154. const getFilePath = (ext) => {
  155. let filePath = null;
  156. for (const name of ptName) {
  157. const tempPath = path.join(tempDir, `${name}.${ext}`);
  158. if (fs.existsSync(tempPath)) {
  159. filePath = tempPath;
  160. break;
  161. }
  162. }
  163. return filePath;
  164. };
  165. // 在解压后的目录中查找文件
  166. const jsonPath = getFilePath("json");
  167. const cssPath = getFilePath("css");
  168. const ttfPath = getFilePath("ttf");
  169. if (!ttfPath) {
  170. console.warn(`⚠️跳过 ${folderName}: 缺少 TTF 文件`);
  171. return null;
  172. }
  173. let iconData = [];
  174. // 优先使用JSON文件
  175. if (jsonPath) {
  176. iconData = processIconData(jsonPath);
  177. }
  178. // 如果没有则尝试CSS文件
  179. else if (cssPath) {
  180. iconData = extractIconsFromCSS(cssPath);
  181. } else {
  182. console.warn(`⚠️ 跳过 ${folderName}: 缺少 ${jsonPath} 或 ${cssPath}`);
  183. return null;
  184. }
  185. if (iconData.length === 0) {
  186. console.warn(`⚠️ ${folderName}: 没有找到图标数据`);
  187. return null;
  188. }
  189. console.log(`✅ ${zipFileName} 找到 ${iconData.length} 个图标`);
  190. // 转换TTF为base64
  191. const base64Data = ttfToBase64(ttfPath);
  192. if (!base64Data) {
  193. console.error(`❌ ${folderName}: TTF转换失败`);
  194. return null;
  195. }
  196. // 为该文件夹创建icons子目录 (使用原始文件夹名称)
  197. ensureDistDir(originalFolderName);
  198. // 生成TypeScript文件 (使用驼峰命名作为变量名,原始名称作为路径)
  199. generateTypeScript(originalFolderName, folderName, iconData);
  200. // 生成SCSS文件 (使用原始名称作为路径和字体名称)
  201. generateSCSS(originalFolderName, base64Data);
  202. return { originalName: originalFolderName, camelName: folderName };
  203. }
  204. // 生成主index.ts文件
  205. function generateIndexTS(actualFolders) {
  206. const imports = actualFolders
  207. .map((folder) => {
  208. const camelName = toCamelCase(folder);
  209. return `import { ${camelName} } from "./${folder}";`;
  210. })
  211. .join("\n");
  212. const exports = `export const icons = {\n${actualFolders
  213. .map((folder) => `\t${toCamelCase(folder)}`)
  214. .join(",\n")}\n};\n`;
  215. const content = `${imports}\n\n${exports}`;
  216. fs.writeFileSync("icons/index.ts", content);
  217. }
  218. // 生成主index.scss文件
  219. function generateIndexSCSS(actualFolders) {
  220. const imports = actualFolders.map((folder) => `@import "./${folder}/index.scss";`).join("\n");
  221. fs.writeFileSync("icons/index.scss", imports + "\n");
  222. }
  223. // 扫描icons目录下的实际文件夹
  224. function getActualIconFolders() {
  225. const iconsDir = "icons";
  226. if (!fs.existsSync(iconsDir)) {
  227. return [];
  228. }
  229. return fs.readdirSync(iconsDir).filter((item) => {
  230. const itemPath = path.join(iconsDir, item);
  231. const stats = fs.statSync(itemPath);
  232. return stats.isDirectory();
  233. });
  234. }
  235. // 主函数
  236. function main() {
  237. console.log("🚀 开始处理字体文件...\n");
  238. // 确保临时目录存在
  239. ensureTempDir();
  240. // 确保icons目录存在
  241. ensureDistDir();
  242. try {
  243. // 获取所有zip文件
  244. const zipFiles = getZipFiles();
  245. // 处理每个zip文件
  246. const processedFolders = [];
  247. for (const zipFile of zipFiles) {
  248. const result = processZipFile(zipFile);
  249. if (result) {
  250. processedFolders.push(result);
  251. }
  252. }
  253. // 扫描icons目录下的实际文件夹
  254. const actualFolders = getActualIconFolders();
  255. if (actualFolders.length > 0) {
  256. // 生成主index文件
  257. generateIndexTS(actualFolders);
  258. generateIndexSCSS(actualFolders);
  259. }
  260. if (processedFolders.length > 0) {
  261. const folderNames = processedFolders.map((f) =>
  262. typeof f === "string" ? f : f.originalName
  263. );
  264. console.log(
  265. `\n🎉 成功处理了 ${processedFolders.length} 个字体包: ${folderNames.join(", ")}`
  266. );
  267. }
  268. } catch (error) {
  269. console.error("❌ 脚本执行出错:", error);
  270. } finally {
  271. cleanupTempDir();
  272. }
  273. }
  274. // 运行脚本
  275. if (require.main === module) {
  276. main();
  277. }