wip: better IPC messaging with the CLI

This commit is contained in:
Igor Randjelovic
2020-11-22 23:57:37 +01:00
parent f6636367ee
commit f937940902
2 changed files with 80 additions and 2 deletions

View File

@ -8,7 +8,8 @@ import {
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import { DefinePlugin, HotModuleReplacementPlugin } from 'webpack';
import { WatchStateLoggerPlugin } from '../plugins/WatchStateLoggerPlugin';
// import { WatchStateLoggerPlugin } from '../plugins/WatchStateLoggerPlugin';
import { WatchStatePlugin } from '../plugins/WatchStatePlugin';
import TerserPlugin from 'terser-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
@ -202,7 +203,8 @@ export default function (config: Config, env: IWebpackEnv): Config {
// ]);
// add the WatchStateLogger plugin used to notify the CLI of build state
config.plugin('WatchStateLoggerPlugin').use(WatchStateLoggerPlugin);
// config.plugin('WatchStateLoggerPlugin').use(WatchStateLoggerPlugin);
config.plugin('WatchStatePlugin').use(WatchStatePlugin);
config.when(env.hmr, (config) => {
config.plugin('HotModuleReplacementPlugin').use(HotModuleReplacementPlugin);

View File

@ -0,0 +1,76 @@
const id = 'WatchStateLoggerPlugin';
const version = 1;
export enum messages {
compilationComplete = 'Webpack compilation complete.',
startWatching = 'Webpack compilation complete. Watching for file changes.',
changeDetected = 'File change detected. Starting incremental webpack compilation...',
}
/**
* This little plugin will report the webpack state through the console.
* So the {N} CLI can get some idea when compilation completes.
*/
export class WatchStatePlugin {
isRunningWatching: boolean;
apply(compiler) {
let isWatchMode = false;
let prevAssets = [];
compiler.hooks.watchRun.tapAsync(id, function (compiler, callback) {
callback();
isWatchMode = true;
console.log(messages.changeDetected);
});
compiler.hooks.afterEmit.tapAsync(id, function (compilation, callback) {
callback();
console.log(
isWatchMode ? messages.startWatching : messages.compilationComplete
);
const assets =
compilation.getStats().toJson(
{
assets: true,
},
true
).assets || [];
const assetList = assets.map((asset) => asset.name);
const emittedAssets = Array.from(compilation.emittedAssets);
const staleAssets = prevAssets.filter((asset) => {
return assetList.includes(asset) === false;
});
// store assets for next compilation
prevAssets = assetList.sort();
notify({
type: 'compilation',
version,
emittedAssets,
staleAssets,
hash: compilation.hash,
});
});
}
}
function notify(message: any) {
if (!process.send) {
return;
}
console.log(`[${id}] Notify: `, message);
process.send(message, (error) => {
if (error) {
console.error(`[${id}] Process Send Error: `, error);
}
return null;
});
}