Deland
Deland

Reputation: 1

How to recognize a compilation is first-time-build or refresh in wepack compile hook 'done'?

I want to collect the build speeds of our project for advancing performance optimization. The indexes include build-speed, devServer-start-speed, and devServer-refresh-speed:

My plan is to write a webpack plugin with compile hook done to collect these indexes.(webpack 5)

The done hook provides a param stats for callback fn, and I can calculate the build speeds by startTime and endTime in the stats object.

But it seems that there is no more info that can distinguish the current compilation is the first-time build or refresh.(we use @pmmmwh/react-refresh-webpack-plugin to optimize the build speed).

Any idea to recognize a compilation is first-time-build or refresh?

Below is my plugin:

class BuildStatsWebpackPlugin {
  constructor(options) {
    this.options = options || {};
  }
  apply(compiler) {
    compiler.hooks.done.tap({ name: 'BuildStatsWebpackPlugin' }, (stats) => {
      const startTime = stats.compilation.startTime;
      const endTime = stats.compilation.endTime;
      const speed = endTime - startTime;

      const buildType = ''; // how to get the type from stats?

      report({
        buildType,
        speed
      });
    });
  }
}

Besides, is there an interface declaration of Stats?

Upvotes: 0

Views: 346

Answers (1)

Moses The Prophet
Moses The Prophet

Reputation: 11

I also need to distinguish between first compilation and recompilation, and found nothing in webpack docs.

I need it to decide if I should run a script using hook-shell-script-webpack-plugin, here's what I came up with:

    new HookShellScriptPlugin({
      thisCompilation: [
        (compilation, compilationParams) => {
          console.log('==================');
          if (compilationParams.contextModuleFactory.resolverFactory.cache.size === 0) {
            console.log('FIRST GENERATION');
            return 'yarn myscript';
          } else {
            console.log('REGENERATION');
          }
          console.log('==================');
        },
      ],
    }),

I'm not sure if and how is it applicable to your situation, but that's the way of solving the problem inside webpack config, using webpack hooks.

It doesn't look like a proper way to solve a problem, but it works for me.

Upvotes: 1

Related Questions