1+ const fs = require ( 'fs' ) ;
2+ const path = require ( 'path' ) ;
3+ const sharp = require ( 'sharp' ) ;
4+ const { execSync } = require ( 'child_process' ) ;
5+
6+ async function generateIcons ( ) {
7+ try {
8+ console . log ( '开始生成图标...' ) ;
9+
10+ // 确保SVG文件存在
11+ const svgPath = path . join ( __dirname , 'assets/icon.svg' ) ;
12+ if ( ! fs . existsSync ( svgPath ) ) {
13+ console . error ( '错误: SVG文件不存在:' , svgPath ) ;
14+ return ;
15+ }
16+
17+ // 读取SVG文件
18+ const svgBuffer = fs . readFileSync ( svgPath ) ;
19+ console . log ( '成功读取SVG文件' ) ;
20+
21+ // 创建不同大小的PNG图像
22+ const sizes = [ 16 , 32 , 48 , 64 , 128 , 256 , 512 ] ;
23+
24+ // 确保目录存在
25+ if ( ! fs . existsSync ( path . join ( __dirname , 'assets' ) ) ) {
26+ fs . mkdirSync ( path . join ( __dirname , 'assets' ) ) ;
27+ }
28+
29+ if ( ! fs . existsSync ( path . join ( __dirname , 'public/icons' ) ) ) {
30+ fs . mkdirSync ( path . join ( __dirname , 'public/icons' ) , { recursive : true } ) ;
31+ }
32+
33+ // 生成各种尺寸的PNG
34+ for ( const size of sizes ) {
35+ try {
36+ console . log ( `生成 ${ size } x${ size } 图标...` ) ;
37+ await sharp ( svgBuffer )
38+ . resize ( size , size )
39+ . png ( )
40+ . toFile ( path . join ( __dirname , `assets/icon-${ size } .png` ) ) ;
41+
42+ // 同时在public目录也生成一份
43+ await sharp ( svgBuffer )
44+ . resize ( size , size )
45+ . png ( )
46+ . toFile ( path . join ( __dirname , `public/icons/icon-${ size } .png` ) ) ;
47+ } catch ( err ) {
48+ console . error ( `生成 ${ size } x${ size } 图标时出错:` , err ) ;
49+ }
50+ }
51+
52+ // 生成主图标文件
53+ try {
54+ console . log ( '生成主图标文件...' ) ;
55+ await sharp ( svgBuffer )
56+ . resize ( 512 , 512 )
57+ . png ( )
58+ . toFile ( path . join ( __dirname , 'assets/icon.png' ) ) ;
59+ } catch ( err ) {
60+ console . error ( '生成主图标文件时出错:' , err ) ;
61+ }
62+
63+ // 生成PWA所需的图标
64+ try {
65+ console . log ( '生成PWA图标...' ) ;
66+ await sharp ( svgBuffer )
67+ . resize ( 192 , 192 )
68+ . png ( )
69+ . toFile ( path . join ( __dirname , 'public/logo192.png' ) ) ;
70+
71+ await sharp ( svgBuffer )
72+ . resize ( 512 , 512 )
73+ . png ( )
74+ . toFile ( path . join ( __dirname , 'public/logo512.png' ) ) ;
75+ } catch ( err ) {
76+ console . error ( '生成PWA图标时出错:' , err ) ;
77+ }
78+
79+ console . log ( '所有PNG图标生成完成!' ) ;
80+
81+ // 生成favicon
82+ try {
83+ console . log ( '生成favicon...' ) ;
84+ // 生成16x16的favicon作为默认图标
85+ await sharp ( svgBuffer )
86+ . resize ( 16 , 16 )
87+ . png ( )
88+ . toFile ( path . join ( __dirname , 'public/favicon.ico' ) ) ;
89+ console . log ( 'Favicon生成完成' ) ;
90+ } catch ( err ) {
91+ console . error ( '生成favicon时出错:' , err ) ;
92+ }
93+
94+ console . log ( '图标生成完成!' ) ;
95+ } catch ( error ) {
96+ console . error ( '生成图标时出错:' , error ) ;
97+ }
98+ }
99+
100+ generateIcons ( ) . then ( ( ) => {
101+ console . log ( '脚本执行完成' ) ;
102+ } ) . catch ( err => {
103+ console . error ( '脚本执行失败:' , err ) ;
104+ } ) ;
0 commit comments