使用 Node.js 脚本自动将阿里 Iconfont 图标库集成到 Flutter 项目

本文提供一个 Node.js 脚本,帮助您轻松将阿里 Iconfont 图标库下载、解压缩并集成到 Flutter 项目中,包括生成 Dart 文件、更新 pubspec.yaml 文件以及打包成跨平台可执行文件。

脚本功能

  1. 将指定目录下的 'download.zip' 文件的云图标库文件解压出来。
  2. 将解压出来的 ttf 文件放到指定的文件夹下。
  3. 根据解压文件中的 html 文件生成对应的 dart 文件。
  4. 将关键变量提取出来,可以在调用脚本时通过命令行方式传入。
  5. 追加 ttf 资源文件路径到 pubspec.yaml 文件下。
  6. 打包依赖可生成 Windows、Linux、macOS 的二进制程序。

使用方法

  1. 下载脚本代码并安装依赖
git clone https://github.com/xxxx/xxxx.git
cd xxxxx
npm install
  1. 运行脚本
node iconfont.js --zipPath=xxx --outputPath=xxx --htmlPath=xxx --ttfPath=xxx --pubspecPath=xxx

参数说明:

  • zipPath: 阿里 Iconfont 图标库的下载压缩包路径
  • outputPath: 解压后 ttf 文件的输出路径
  • htmlPath: 解压后 html 文件的路径
  • ttfPath: 生成的 dart 文件的输出路径
  • pubspecPath: Flutter 项目的 pubspec.yaml 文件路径
  1. 打包二进制程序
npm run build

打包后会在 dist 目录下生成可执行文件,分别为:

  • iconfont-win.exe (Windows)
  • iconfont-mac (MacOS)
  • iconfont-linux (Linux)

示例

// iconfont.js
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const { execSync } = require('child_process');

const argv = require('yargs').argv;

const zipPath = argv.zipPath;
const outputPath = argv.outputPath;
const htmlPath = argv.htmlPath;
const ttfPath = argv.ttfPath;
const pubspecPath = argv.pubspecPath;

// 解压缩 zip 文件
const outputDir = path.join(__dirname, outputPath);
const archive = archiver('zip');
const output = fs.createWriteStream(path.join(outputDir, 'temp.zip'));
archive.pipe(output);
archive.directory(zipPath, 'fonts');
archive.finalize();

// 提取 ttf 文件
const ttfDir = path.join(outputDir, 'fonts');
const files = fs.readdirSync(ttfDir);
files.forEach(file => {
  if (path.extname(file) === '.ttf') {
    fs.renameSync(path.join(ttfDir, file), path.join(outputDir, file));
  }
});

// 生成 dart 文件
const htmlFile = fs.readFileSync(path.join(htmlPath, 'iconfont.html'), 'utf8');
const icons = htmlFile.match(/<i class="(.+?)"/g).map(icon => icon.replace(/<i class="(.+?)"/g, '$1'));
const dartContent = `
class IconfontIcons {
  ${icons.map(icon => `static const IconData ${icon} = IconData(0xe${icon.charCodeAt(0).toString(16)}, fontFamily: 'Iconfont');`).join('
  ')}
}
`;
fs.writeFileSync(path.join(ttfPath, 'iconfont_icons.dart'), dartContent);

// 更新 pubspec.yaml 文件
const pubspecContent = fs.readFileSync(pubspecPath, 'utf8');
const updatedPubspecContent = pubspecContent.replace(/flutter:
  assets:/, `flutter:
  assets:
    - ${outputPath}`);
fs.writeFileSync(pubspecPath, updatedPubspecContent);

// 打包二进制程序
// ...

注意:

  • 脚本需要安装 archiveryargs 等依赖。
  • 脚本中的路径需要根据实际情况进行调整。
  • 脚本中的代码仅供参考,具体实现可能需要根据实际需求进行修改。

总结

使用这个 Node.js 脚本,您可以轻松将阿里 Iconfont 图标库集成到 Flutter 项目中,从而提高开发效率。脚本可以帮助您自动完成解压缩、生成 Dart 文件、更新 pubspec.yaml 文件等操作,并提供跨平台的可执行文件,方便您在不同平台上使用。

使用 Node.js 脚本自动将阿里 Iconfont 图标库集成到 Flutter 项目

原文地址: https://www.cveoy.top/t/topic/ly6e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录