Saturday, 25 June 2022

How to convert Webpack 4 plugin to Webpack 5

How do I convert this plugin that worked on Webpack 4 to Webpack 5?

More specifically, the plugin() function no longer works. How do I replace this to support Webpack 5?

const ConstDependency = require('webpack/lib/dependencies/ConstDependency');
const NullFactory = require('webpack/lib/NullFactory');

class StaticAssetPlugin {
  constructor(localization, options, failOnMissing) {
    this.options = options || {};
    this.localization = localization;
    this.functionName = this.options.functionName || '__';
    this.failOnMissing = !!this.options.failOnMissing;
    this.hideMessage = this.options.hideMessage || false;
  }

  apply(compiler) {
    const { localization } = this;
    const name = this.functionName;

    compiler.plugin('compilation', (compilation, params) => {
      compilation.dependencyFactories.set(ConstDependency, new NullFactory());
      compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
    });

    compiler.plugin('compilation', (compilation, data) => {
      data.normalModuleFactory.plugin('parser', (parser, options) => {
        // should use function here instead of arrow function due to save the Tapable's context
        parser.plugin(`call ${name}`, function staticAssetPlugin(expr) {
          let param;
          let defaultValue;
          switch (expr.arguments.length) {
            case 1:
              param = this.evaluateExpression(expr.arguments[0]);
              if (!param.isString()) return;
              defaultValue = param = param.string;
              break;
            default:
              return;
          }
          let result = localization(param);

          const dep = new ConstDependency(JSON.stringify(result), expr.range);
          dep.loc = expr.loc;
          this.state.current.addDependency(dep);
          return true;
        });
      });
    });
  }
}

module.exports = StaticAssetPlugin;

Are there any migration guides for plugin creation that I can follow? Any help would be greatly appreciated.

Thanks.



from How to convert Webpack 4 plugin to Webpack 5

No comments:

Post a Comment