cordova-13/scripts/dev.ts
2024-12-16 20:56:14 +08:00

86 lines
2.2 KiB
TypeScript
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.

/**
* @author Taoya
* @date 2022/5/23
* @Description: 构建开发环境包
*/
import * as fs from 'fs';
import { resolve } from 'path';
import { exec, ChildProcess } from 'child_process';
import chalk from 'chalk';
import logger from 'consola'
interface BuildResult {
success: boolean;
message: string;
}
async function buildAndroid(): Promise<BuildResult> {
return new Promise((resolve) => {
const buildProcess = exec('npx cordova run android', (error, stdout, stderr) => {
if (error) {
resolve({
success: false,
message: error.message
});
return;
}
if (stdout.includes('BUILD SUCCESSFUL')) {
resolve({
success: true,
message: 'BUILD SUCCESSFUL'
});
} else {
resolve({
success: false,
message: stderr || '构建失败'
});
}
});
// 输出构建日志
buildProcess.stdout?.on('data', (data: string) => {
console.log(chalk.green(data));
});
});
}
async function main(): Promise<void> {
try {
const packageName: string = 'dev.apk';
const distPath: string = './dist';
const outputPath: string = './platforms/android/app/build/outputs/apk/debug/app-debug.apk';
// 检查dist目录是否存在不存在则创建
if (!fs.existsSync(distPath)) {
fs.mkdirSync(distPath, { recursive: true });
}
// 构建android应用
const buildResult = await buildAndroid();
if (buildResult.success) {
logger.log('info', '构建成功');
// 如果目标文件已存在则删除
if (fs.existsSync(`${distPath}/${packageName}`)) {
fs.unlinkSync(`${distPath}/${packageName}`);
}
// 移动构建产物
fs.renameSync(outputPath, `${distPath}/${packageName}`);
} else {
logger.log('error', `构建失败: ${buildResult.message}`);
process.exit(1);
}
} catch (error) {
logger.log('error', `执行失败: ${error instanceof Error ? error.message : '未知错误'}`);
process.exit(1);
}
}
// 执行主函数
main().catch(error => {
logger.log('error', `意外错误: ${error instanceof Error ? error.message : '未知错误'}`);
process.exit(1);
});