@falconix/ymcli
Version:
A CLI tool for creating and building multi-platform Vue projects
105 lines (89 loc) • 3.18 kB
JavaScript
const path = require('path');
const fs = require('fs-extra');
const { pathExists, createDirectory, runCommand } = require('../utils');
/**
* 构建指定平台的项目
* @param {string} platform 平台 (pc, web, mobile)
* @param {string} projectPath 项目根路径
*/
async function buildPlatform(platform, projectPath) {
const validPlatforms = ['web', 'mobile'];
// const validPlatforms = ['pc', 'web', 'mobile'];
if (!validPlatforms.includes(platform)) {
console.error(`Error: Invalid platform "${platform}". Valid platforms are: ${validPlatforms.join(', ')}`);
return false;
}
const platformPath = path.join(projectPath, platform);
if (!(await pathExists(platformPath))) {
console.error(`Error: Platform directory "${platform}" not found in project.`);
return false;
}
const packageJsonPath = path.join(platformPath, 'package.json');
if (!(await pathExists(packageJsonPath))) {
console.error(`Error: No package.json found in ${platform} directory.`);
return false;
}
try {
// 执行构建命令
console.log(`Building ${platform} project...`);
await runCommand('pnpm', ['run', 'build'], { cwd: platformPath });
// 创建 dist 目录
const distRoot = path.join(projectPath, 'dist');
await createDirectory(distRoot);
// 构建后的目录
const platformDist = path.join(platformPath, 'dist');
if (!(await pathExists(platformDist))) {
console.error(`Error: Build output not found for ${platform}.`);
return false;
}
// 目标目录
const targetDist = path.join(distRoot, platform);
// 复制构建结果
await fs.copy(platformDist, targetDist, { overwrite: true });
console.log(`Successfully built ${platform} project. Output: ${targetDist}`);
return true;
} catch (error) {
console.error(`Error building ${platform} project:`, error);
return false;
}
}
/**
* 构建项目
* @param {string} platform 平台 (pc, web, mobile, 或不指定构建全部)
* @param {object} options 选项
*/
async function buildProject(platform, options) {
const projectPath = path.resolve(options.project);
if (!(await pathExists(projectPath))) {
console.error(`Error: Project directory "${projectPath}" not found.`);
process.exit(1);
}
try {
if (platform) {
// 构建指定平台
const success = await buildPlatform(platform, projectPath);
process.exit(success ? 0 : 1);
} else {
// 构建所有平台
console.log('Building all platforms...');
const platforms = ['web', 'mobile'];
// const platforms = ['pc', 'web', 'mobile'];
let allSuccess = true;
for (const p of platforms) {
const success = await buildPlatform(p, projectPath);
allSuccess = allSuccess && success;
}
if (allSuccess) {
console.log('All platforms built successfully.');
process.exit(0);
} else {
console.log('Some platforms failed to build.');
process.exit(1);
}
}
} catch (error) {
console.error('Error during build process:', error);
process.exit(1);
}
}
module.exports = buildProject;