Javascript 网页包自定义插件。使用AST在react组件中插入属性

Javascript 网页包自定义插件。使用AST在react组件中插入属性,javascript,webpack,webpack-4,webpack-plugin,Javascript,Webpack,Webpack 4,Webpack Plugin,我需要在网页包编译时插入数据属性以响应组件。 例如,我有一个组件: export const MyComponent = (props: any) => { return ( <div>bla bla</div> ); }; 我自己还没有写过一个网页包插件,但我发现它似乎做了一些相关的事情。可能会对您有所帮助,因为它使用以下函数向任何标记添加属性 function addAttr(compilation, tags, key, val) {

我需要在网页包编译时插入数据属性以响应组件。 例如,我有一个组件:

export const MyComponent = (props: any) => {
  return (
    <div>bla bla</div>
  );
};

我自己还没有写过一个网页包插件,但我发现它似乎做了一些相关的事情。可能会对您有所帮助,因为它使用以下函数向任何标记添加属性

function addAttr(compilation, tags, key, val) {
    if (!tags || !tags.length) {
        return;
    }
    forEach(tags, function (tag, index) {
        var value = val;
        if (typeof val === "function") {
            value = val(tag, compilation, index);
        } else if (typeof val === 'object') {
            value = JSON.stringify(val);
        }
        tag.attributes[key] = value;
    });
}

我自己从来没有为webpack编写过插件,但我目前正在努力配置它们,这就是我如何偶然发现您的问题的原因。
export class ReactAttrGeneratorPlugin implements webpack.Plugin {
  public apply({ hooks }: webpack.Compiler) {

    hooks.compilation.tap(
      "ReactAttrGeneratorPlugin",
      (compilation) => {
        compilation.dependencyFactories.set(ConstDependency, new NullFactory());
        compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
      });

    hooks.normalModuleFactory.tap('ReactAttrGeneratorPlugin', (factory) => {
      factory.hooks.parser.for('javascript/auto').tap('ReactAttrGeneratorPlugin', (parser, options) => {
        parser.hooks.statement.tap('ReactAttrGeneratorPlugin', (statement:any) => {
          if (this.isOwnComponent(parser) && statement.type === 'ReturnStatement') {

            const div = statement.argument.arguments[0];

            /** What do I need here, to insert attribute to div? **/

          }
        });
      });
    });
  }

  private isOwnComponent(parser: any) {
    return parser.state &&
      parser.state.module &&
      parser.state.module.resource.indexOf('node_modules') === -1 &&
      parser.state.module.resource.endsWith('tsx');
  }
}
function addAttr(compilation, tags, key, val) {
    if (!tags || !tags.length) {
        return;
    }
    forEach(tags, function (tag, index) {
        var value = val;
        if (typeof val === "function") {
            value = val(tag, compilation, index);
        } else if (typeof val === 'object') {
            value = JSON.stringify(val);
        }
        tag.attributes[key] = value;
    });
}