使用 Node.js 脚本下载并集成阿里巴巴矢量图标库到 Flutter 项目
以下是一个使用 Node.js 编写的脚本,可以自动完成从下载阿里巴巴矢量图标库的压缩包,到解压缩并提取 ttf 文件,生成对应的 Flutter 图标类文件,最后将图标集成到 Flutter 项目中的整个流程。
const https = require('https');
const fs = require('fs');
const path = require('path');
const unzipper = require('unzipper');
const cheerio = require('cheerio');
// 从命令行参数中获取关键变量
const [, , ICONFONT_URL, TTF_DIR, DART_DIR] = process.argv;
// 下载压缩包并解压
https.get(ICONFONT_URL, response => {
response.pipe(unzipper.Extract({ path: './temp' }))
.on('finish', () => {
console.log('解压完成');
// 遍历temp目录中的所有文件
fs.readdir('./temp', (err, files) => {
if (err) throw err;
files.forEach(file => {
const filePath = path.resolve('./temp', file);
const ext = path.extname(file);
if (ext === '.ttf') {
// 复制ttf文件到指定目录
const ttfPath = path.resolve(TTF_DIR, file);
fs.copyFileSync(filePath, ttfPath);
console.log(`复制${file}到${TTF_DIR}`);
// 生成对应的dart文件
const iconName = path.basename(file, '.ttf');
const dartPath = path.resolve(DART_DIR, `${iconName}.dart`);
const html = fs.readFileSync(path.resolve('./temp', 'demo_index.html'));
const $ = cheerio.load(html.toString());
const symbols = $('symbol');
let content = '';
symbols.each((i, symbol) => {
const id = $(symbol).attr('id');
const code = id.split('-').pop();
content += ` static const IconData ${id} = IconData(0x${code}, fontFamily: '${iconName}');
`;
});
const data = `import 'package:flutter/widgets.dart';
class ${iconName} {
${content}}`;
fs.writeFileSync(dartPath, data);
console.log(`生成${iconName}.dart文件到${DART_DIR}`);
}
});
});
});
});
运行方式:
node download-iconfont.js https://at.alicdn.com/t/font_1234567.zip ./assets/fonts ./lib/icons
其中,第一个参数是 iconfont 下载链接,第二个参数是 ttf 文件存放目录,第三个参数是 Dart 文件存放目录。
原文地址: https://www.cveoy.top/t/topic/lyK1 著作权归作者所有。请勿转载和采集!