bdwain
bdwain

Reputation: 1745

how to modify webpack 5 main template with plugin

In webpack 4, I had a plugin to modify the webpack runtime that looked like this

function MyPlugin() {}
MyPlugin.prototype.apply = function (compiler) {
    compiler.hooks.compilation.tap(
        'MyPlugin',
        function (compilation) {
            compilation.mainTemplate.hooks.requireExtensions.tap(
                'MyPlugin',
                (source) =>
                source.replace(
                    '__webpack_require.n = ....',
                    myNewCode
                )
            );
        }
    );
};

This stopped working in webpack 5, and now the source param is always empty. The documentation is a bit lacking on this area. Is it still possible to hook into the build like this? Do I just need a new plugin hook or something?

Upvotes: 1

Views: 723

Answers (1)

bdwain
bdwain

Reputation: 1745

I was able to get it working

MyPlugin.prototype.apply = function (compiler) {
  compiler.hooks.compilation.tap(
    'MyPlugin',
          function (compilation) {
      compilation.hooks.processAssets.tapPromise(
        {
          name: 'MyPlugin',
          stage:
            compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
        },
        async (assets) => {
          const oldSource = assets['runtime.js'];
          const { ReplaceSource } = compiler.webpack.sources;
          const newSource = new ReplaceSource(oldSource, 'MyPlugin');

          const start = oldSource.source().indexOf(codeToReplace);
          const end = start + codeToReplace.length;

          newSource.replace(start, end, newCode, 'MyPlugin');
          await compilation.updateAsset('runtime.js', newSource);
        }
      );
    }
  );
};

Upvotes: 2

Related Questions