| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- /**
- * PWA 图标生成脚本
- *
- * 使用说明:
- * 1. 准备一个 1024x1024 的原始图标文件(推荐使用 PNG 或 SVG)
- * 2. 将文件命名为 icon-source.png 并放在 public 目录
- * 3. 运行: node scripts/generate-icons.js
- *
- * 如果没有安装 sharp,请先安装:
- * npm install -D sharp
- */
- import fs from 'fs';
- import path from 'path';
- import { fileURLToPath } from 'url';
- // 获取当前文件的目录(ES 模块中需要手动获取 __dirname)
- const __filename = fileURLToPath(import.meta.url);
- const __dirname = path.dirname(__filename);
- // 检查是否安装了 sharp
- let sharp;
- try {
- const sharpModule = await import('sharp');
- sharp = sharpModule.default;
- } catch (error) {
- console.error('❌ 未安装 sharp 库');
- console.log('请运行: npm install -D sharp');
- process.exit(1);
- }
- // 图标尺寸配置
- const sizes = [72, 96, 128, 144, 152, 192, 384, 512];
- // 输入和输出目录
- const sourceIcon = path.join(__dirname, '../public/icon-source.png');
- const outputDir = path.join(__dirname, '../public/icons');
- // 创建输出目录
- if (!fs.existsSync(outputDir)) {
- fs.mkdirSync(outputDir, { recursive: true });
- }
- // 检查源文件是否存在
- if (!fs.existsSync(sourceIcon)) {
- console.error(`❌ 源图标文件不存在: ${sourceIcon}`);
- console.log('\n请准备一个 1024x1024 的图标文件:');
- console.log('1. 命名为 icon-source.png');
- console.log('2. 放在 public 目录下');
- console.log('3. 重新运行此脚本');
- process.exit(1);
- }
- // 生成图标
- async function generateIcons() {
- console.log('🎨 开始生成 PWA 图标...\n');
- try {
- for (const size of sizes) {
- const outputPath = path.join(outputDir, `icon-${size}x${size}.png`);
-
- await sharp(sourceIcon)
- .resize(size, size, {
- fit: 'contain',
- background: { r: 15, g: 23, b: 42, alpha: 1 } // 深色背景
- })
- .png({ quality: 90 })
- .toFile(outputPath);
-
- console.log(`✅ 生成 ${size}x${size} 图标`);
- }
- // 生成 Apple Touch Icon (180x180)
- const appleTouchIcon = path.join(__dirname, '../public/apple-touch-icon.png');
- await sharp(sourceIcon)
- .resize(180, 180, {
- fit: 'contain',
- background: { r: 15, g: 23, b: 42, alpha: 1 }
- })
- .png({ quality: 90 })
- .toFile(appleTouchIcon);
- console.log('✅ 生成 Apple Touch Icon (180x180)');
- // 生成 Favicon (32x32)
- const favicon = path.join(__dirname, '../public/favicon.ico');
- await sharp(sourceIcon)
- .resize(32, 32)
- .png()
- .toFile(favicon);
- console.log('✅ 生成 Favicon (32x32)');
- console.log('\n🎉 所有图标生成完成!');
- console.log(`📁 输出目录: ${outputDir}`);
- } catch (error) {
- console.error('❌ 生成图标时出错:', error);
- process.exit(1);
- }
- }
- // 运行脚本
- generateIcons();
|