Node.js 脚本:阿里 Iconfont 图标库解压缩、生成 Dart 文件、整合 Flutter 项目
使用 Node.js 脚本自动整合阿里 Iconfont 图标库到 Flutter 项目
该脚本可以帮助您自动完成以下操作:
- 解压缩指定目录下的
download.zip文件,提取阿里 Iconfont 图标库文件。 - 将解压缩后的
.ttf文件复制到指定的文件夹。 - 根据解压缩文件中的
.html文件生成对应的 Dart 文件。 - 将关键变量提出来,可以在调用脚本时通过命令行传入。
- 将
.ttf资源文件路径添加到pubspec.yaml文件中。 - 附加打包依赖,生成 Windows、Linux、macOS 的二进制程序。
注意: 由于安全原因,该脚本不包含如何下载阿里的 iconfont 图标压缩包的步骤。您需要自行获取该压缩包并将其放到指定的目录下。
代码示例
const fs = require('fs');
const path = require('path');
const unzip = require('unzip');
const { exec } = require('child_process');
// 1. 解压缩 zip 文件
const unzipFile = (sourcePath, targetPath) => {
fs.createReadStream(sourcePath).pipe(unzip.Extract({ path: targetPath }));
};
// 2. 复制 ttf 文件到指定目录下
const copyTTFFile = (sourcePath, targetPath) => {
fs.copyFileSync(sourcePath, targetPath);
};
// 3. 生成 dart 文件
const generateDartFile = (htmlPath, dartPath) => {
// TODO: 根据 html 文件生成 dart 文件逻辑
};
// 4. 获取命令行参数
const args = process.argv.slice(2);
const downloadPath = args[0]; // 下载的 zip 文件路径
const targetPath = args[1]; // 解压缩后的目标文件夹路径
const ttfPath = args[2]; // 复制 ttf 文件的目标文件夹路径
const htmlPath = args[3]; // 生成 dart 文件的 html 文件路径
const dartPath = args[4]; // 生成的 dart 文件路径
// 5. 解压缩 zip 文件
unzipFile(downloadPath, targetPath);
// 6. 复制 ttf 文件到指定目录下
const ttfFilePath = path.join(targetPath, 'iconfont.ttf');
copyTTFFile(ttfFilePath, ttfPath);
// 7. 生成 dart 文件
generateDartFile(htmlPath, dartPath);
// 8. 追加 tff 资源文件路径到 pubspec.yaml 文件下
const yamlPath = path.join(__dirname, 'pubspec.yaml');
fs.appendFileSync(yamlPath, `
- ${ttfPath}`);
// 9. 打包依赖生成二进制程序
// TODO: 实现打包依赖生成二进制程序的逻辑
使用方法
- 将以上代码保存为一个
js文件,例如iconfont.js。 - 在命令行中执行该脚本,并传入以下参数:
node iconfont.js download.zip target ttf html dart
其中:
download.zip: 下载的 zip 文件路径。target: 解压缩后的目标文件夹路径。ttf: 复制 ttf 文件的目标文件夹路径。html: 生成 dart 文件的 html 文件路径。dart: 生成的 dart 文件路径。
注意事项
- 该脚本需要安装
unzip和child_process模块,可以使用npm install unzip child_process命令进行安装。 generateDartFile函数需要根据实际情况进行实现,以将.html文件转换为 Dart 文件。打包依赖生成二进制程序部分需要根据实际情况进行实现。- 请确保您已将
download.zip文件放到指定的目录下。
示例
假设您将 download.zip 文件放在 /home/user/downloads 目录下,并希望将解压缩后的文件放到 /home/user/projects/flutter_app/assets/icons 目录下,那么您可以使用以下命令执行脚本:
node iconfont.js /home/user/downloads/download.zip /home/user/projects/flutter_app/assets/icons /home/user/projects/flutter_app/assets/fonts /home/user/projects/flutter_app/lib/icons/iconfont.dart /home/user/projects/flutter_app/lib/icons
该脚本将自动解压缩 download.zip 文件,并将 .ttf 文件复制到 /home/user/projects/flutter_app/assets/fonts 目录下,生成 iconfont.dart 文件,并将其添加到 pubspec.yaml 文件中。
希望该脚本能够帮助您更方便地使用阿里 Iconfont 图标库。如果您有任何问题,请随时提出。
原文地址: https://www.cveoy.top/t/topic/ly6v 著作权归作者所有。请勿转载和采集!