Display build progress with ProgressPlugin
ProgressPlugin Build Progress Display
ProgressPlugin is a built-in Webpack plugin used to display progress information during the build process. It provides real-time feedback on compilation progress, including module processing, dependency analysis, code generation, and other stages, helping developers intuitively understand the build status.
Basic Usage
To enable it, simply import ProgressPlugin and add it to the plugins array in the Webpack configuration file:
const webpack = require('webpack');
module.exports = {
// ...other configurations
plugins: [
new webpack.ProgressPlugin()
]
};
After running the build command, the terminal will display progress information similar to:
[====================] 90% building
Configuration Options
ProgressPlugin supports various configuration parameters to customize display behavior:
new webpack.ProgressPlugin({
activeModules: true, // Show active modules
entries: true, // Display entry information
modules: false, // Hide module information
modulesCount: 5000, // Start displaying when module count exceeds 5000
profile: false, // Disable performance profiling
dependencies: true, // Show dependency information
dependenciesCount: 10000 // Start displaying when dependency count exceeds 10000
})
Custom Handler Function
You can fully customize progress display by passing a handler function:
new webpack.ProgressPlugin((percentage, message, ...args) => {
console.log(`${Math.floor(percentage * 100)}%`, message, ...args);
// Perform specific actions when build completes
if (percentage === 1) {
console.log('Build complete, starting development server...');
}
});
The handler function receives the following parameters:
percentage
: Number between 0 and 1 representing progressmessage
: Current stage description...args
: Additional information
Advanced Application Example
Combine with the chalk library to create colored progress bars:
const chalk = require('chalk');
const readline = require('readline');
let lastState = null;
let lastStateTime = null;
new webpack.ProgressPlugin((percentage, msg) => {
const state = msg;
const progress = Math.floor(percentage * 100);
// Update only when state changes or after 1 second
if (state !== lastState || Date.now() - lastStateTime > 1000) {
lastState = state;
lastStateTime = Date.now();
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0);
let line = chalk.green.bold(`[${'='.repeat(progress/2)}${' '.repeat(50-progress/2)}] `);
line += chalk.yellow(`${progress}% `);
line += chalk.blue(state);
process.stdout.write(line);
}
if (percentage === 1) {
process.stdout.write('\n\n');
}
});
Performance Considerations
In large projects, ProgressPlugin may introduce slight performance overhead. Optimize with these approaches:
- Use only in development environment:
plugins: [
process.env.NODE_ENV === 'development' && new webpack.ProgressPlugin()
].filter(Boolean)
- Reduce update frequency:
let lastUpdate = 0;
new webpack.ProgressPlugin((percentage) => {
const now = Date.now();
if (now - lastUpdate > 100 || percentage === 1) {
updateProgressBar(percentage);
lastUpdate = now;
}
});
Integration with Other Tools
ProgressPlugin can work with webpack-dev-server:
devServer: {
setupMiddlewares: (middlewares, devServer) => {
if (!devServer) {
throw new Error('webpack-dev-server is not defined');
}
// Custom middleware to handle progress information
middlewares.unshift({
name: 'progress-middleware',
path: '/progress',
middleware: (req, res) => {
// Return current build progress
res.json({ progress: currentProgress });
}
});
return middlewares;
}
}
Best Practices in Real Projects
- Environment-specific configuration:
const progressPlugin = new webpack.ProgressPlugin(
process.env.NODE_ENV === 'production'
? simpleHandler
: detailedHandler
);
function simpleHandler(percentage) {
if (percentage === 1) {
console.log('Build complete');
}
}
function detailedHandler(percentage, msg) {
console.log(`${(percentage * 100).toFixed(1)}% ${msg}`);
}
- Usage with multiple compilers:
const compiler = webpack([
{
entry: './app.js',
plugins: [new webpack.ProgressPlugin({ name: 'Client' })]
},
{
entry: './server.js',
plugins: [new webpack.ProgressPlugin({ name: 'Server' })]
}
]);
In-Depth Analysis of Progress Information
ProgressPlugin provides multi-dimensional progress information:
- Module processing phase:
[==== ] 25% building
[======== ] 50% building
[============ ] 75% building
[==================] 100% building
- Dependency optimization phase:
[==== ] 20% optimizing dependencies
[======== ] 40% optimizing dependencies
[============ ] 60% optimizing dependencies
[================ ] 80% optimizing dependencies
[==================] 100% optimizing dependencies
- Code generation phase:
[==== ] 30% code generation
[======== ] 60% code generation
[============ ] 90% code generation
[==================] 100% code generation
Custom Progress Event Handling
Extend ProgressPlugin functionality using Webpack's hooks system:
compiler.hooks.compilation.tap('ProgressPluginExtension', (compilation) => {
compilation.hooks.buildModule.tap('ProgressPluginExtension', (module) => {
console.log(`Building module: ${module.identifier()}`);
});
compilation.hooks.failedModule.tap('ProgressPluginExtension', (module) => {
console.error(`Module build failed: ${module.identifier()}`);
});
});
Progress Visualization
Integrate build progress into frontend interfaces:
// webpack.config.js
const socket = require('socket.io')();
new webpack.ProgressPlugin((percentage) => {
socket.emit('progress', { percentage });
});
// Client-side code
const socket = io();
const progressBar = document.getElementById('progress-bar');
socket.on('progress', ({ percentage }) => {
progressBar.style.width = `${percentage * 100}%`;
});
Multi-Phase Progress Handling
For complex multi-phase builds, create phased progress:
const phases = [
{ name: 'Initialization', weight: 0.1 },
{ name: 'Compilation', weight: 0.6 },
{ name: 'Optimization', weight: 0.2 },
{ name: 'Asset Generation', weight: 0.1 }
];
let currentPhase = 0;
let phaseProgress = 0;
new webpack.ProgressPlugin((percentage) => {
const phase = phases[currentPhase];
phaseProgress = percentage;
let totalProgress = 0;
for (let i = 0; i < currentPhase; i++) {
totalProgress += phases[i].weight;
}
totalProgress += phase.weight * phaseProgress;
console.log(`[${phase.name}] ${(totalProgress * 100).toFixed(1)}%`);
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn