exam11/package-windows-portable.js
2025-09-09 03:17:43 +08:00

118 lines
3.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
// 创建一个兼容Node.js 12的删除文件夹函数
function deleteFolderRecursive(dir) {
if (fs.existsSync(dir)) {
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const curPath = path.join(dir, file);
if (fs.lstatSync(curPath).isDirectory()) {
// 递归删除子文件夹
deleteFolderRecursive(curPath);
} else {
// 删除文件
fs.unlinkSync(curPath);
}
}
// 删除空文件夹
fs.rmdirSync(dir);
}
}
// 创建打包前的准备工作
function prepareForBuild() {
console.log('开始准备Windows 7便携应用打包...');
try {
// 清理之前的构建文件 - 使用兼容Node.js 12的方法
const buildDir = path.join(__dirname, 'dist_electron');
if (fs.existsSync(buildDir)) {
console.log('清理之前的构建文件...');
deleteFolderRecursive(buildDir);
}
// 确保data目录存在便携应用需要
const dataDir = path.join(__dirname, 'data');
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir);
fs.writeFileSync(path.join(dataDir, '.gitignore'), '*\n!.gitignore');
console.log('创建data目录完成');
}
console.log('准备工作完成');
} catch (error) {
console.error('准备工作失败:', error);
process.exit(1);
}
}
// 临时修改package.json的main字段
function updatePackageJson() {
const packageJsonPath = path.join(__dirname, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
// 保存原始的main字段值
const originalMain = packageJson.main;
// 修改main字段为正确的路径
packageJson.main = 'src/background/main.js';
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
console.log('已临时修改package.json的main字段为: src/background/main.js');
// 返回恢复函数
return function restorePackageJson() {
packageJson.main = originalMain;
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
console.log('已恢复package.json的main字段为原始值');
};
}
// 执行打包命令
function buildPortableApp() {
console.log('开始构建Windows 7便携应用...');
// 临时修改package.json
const restorePackageJson = updatePackageJson();
try {
// 设置构建环境变量
process.env.WIN_CSC_LINK = '';
process.env.WIN_CSC_KEY_PASSWORD = '';
// 执行构建命令
execSync(
'npm run electron:build -- --win portable --ia32 --x64 --publish never',
{ stdio: 'inherit' }
);
console.log('Windows 7便携应用构建完成');
console.log('构建产物位于 dist_electron 目录');
} catch (error) {
console.error('构建失败:', error);
// 确保即使构建失败也恢复package.json
restorePackageJson();
process.exit(1);
} finally {
// 无论构建成功与否都恢复package.json
restorePackageJson();
}
}
// 主函数
function main() {
console.log("==== Windows 7便携应用打包工具 ====");
console.log("Node.js版本:", process.version);
console.log("Electron版本: 11.5.0");
console.log("Vue版本: 2.6.11");
prepareForBuild();
buildPortableApp();
}
// 执行主函数
main();