// src/BuildProgressPlugin.js
class BuildProgressPlugin {
constructor(options = {}) {
this.showModuleProgress = options.showModuleProgress !== false;
this.moduleProgressInterval = options.moduleProgressInterval || 100;
}
apply(compiler) {
const startTime = {};
let moduleCount = 0;
// 编译开始
compiler.hooks.compile.tap('BuildProgressPlugin', () => {
startTime.compile = Date.now();
moduleCount = 0;
console.log('\n🚀 开始构建...');
});
// 获取 compilation
compiler.hooks.compilation.tap('BuildProgressPlugin', (compilation) => {
// 模块构建开始
compilation.hooks.buildModule.tap('BuildProgressPlugin', (module) => {
moduleCount++;
if (this.showModuleProgress &&
moduleCount % this.moduleProgressInterval === 0) {
process.stdout.write(`\r📦 正在构建模块: ${moduleCount} 个`);
}
});
// 所有模块构建完成
compilation.hooks.finishModules.tap('BuildProgressPlugin', (modules) => {
const duration = ((Date.now() - startTime.compile) / 1000).toFixed(2);
console.log(`\n✅ 模块构建完成: 共 ${modules.size} 个模块 (耗时 ${duration}s)`);
});
// 优化阶段
compilation.hooks.optimize.tap('BuildProgressPlugin', () => {
console.log('🔧 开始优化...');
});
// chunk 优化完成
compilation.hooks.afterOptimizeChunks.tap('BuildProgressPlugin', (chunks) => {
console.log(`📊 生成了 ${chunks.size} 个 chunk`);
});
});
// 资源输出前
compiler.hooks.emit.tapAsync('BuildProgressPlugin', (compilation, callback) => {
const assetCount = Object.keys(compilation.assets).length;
console.log(`📝 准备输出 ${assetCount} 个文件...`);
callback();
});
// 构建完成
compiler.hooks.done.tap('BuildProgressPlugin', (stats) => {
const totalTime = ((Date.now() - startTime.compile) / 1000).toFixed(2);
console.log('\n' + '='.repeat(50));
if (stats.hasErrors()) {
const errors = stats.compilation.errors.length;
console.log(`❌ 构建失败: ${errors} 个错误 (耗时 ${totalTime}s)`);
this.printErrors(stats.compilation.errors);
} else if (stats.hasWarnings()) {
const warnings = stats.compilation.warnings.length;
console.log(`⚠️ 构建完成: ${warnings} 个警告 (耗时 ${totalTime}s)`);
this.printWarnings(stats.compilation.warnings);
} else {
console.log(`✨ 构建成功! (耗时 ${totalTime}s)`);
}
console.log('='.repeat(50) + '\n');
});
// 构建失败
compiler.hooks.failed.tap('BuildProgressPlugin', (error) => {
console.error('\n💥 构建失败:', error.message);
});
}
printErrors(errors) {
console.log('\n错误详情:');
errors.slice(0, 3).forEach((error, index) => {
console.log(`\n${index + 1}. ${error.message}`);
});
if (errors.length > 3) {
console.log(`\n... 还有 ${errors.length - 3} 个错误`);
}
}
printWarnings(warnings) {
console.log('\n警告详情:');
warnings.slice(0, 3).forEach((warning, index) => {
console.log(`\n${index + 1}. ${warning.message}`);
});
if (warnings.length > 3) {
console.log(`\n... 还有 ${warnings.length - 3} 个警告`);
}
}
}
module.exports = BuildProgressPlugin;