javascript - Webpack 自定义插件。使用 AST 在 React 组件中插入属性

标签 javascript webpack webpack-4 webpack-plugin

我需要在 webpack 编译时插入 data-attr 来响应组件。 例如我有这个组件:

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

编译后我需要这个:

export const MyComponent = (props: any) => {
  return (
    <div data-attr="some data">bla bla</div>
  );
};

我已经写了下面的插件(我认为这几乎是完整的,但我找不到插入属性的方法):

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');
  }
}

最佳答案

我自己还没有写过 webpack 插件,但我发现 https://github.com/jantimon/html-webpack-plugin/issues/538html-webpack-plugin 似乎做了一些相关的事情。 source code of that package 可能对您有帮助,因为它通过使用以下函数向 any 标记添加属性

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;
    });
}

关于javascript - Webpack 自定义插件。使用 AST 在 React 组件中插入属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58011241/

相关文章:

javascript - 经典工具包的 ExtJS 地理定位用法

javascript - CRUD 更新无法正常运行

javascript - JS 中的行交换

javascript - Vuejs Webpack压缩插件不压缩

webpack - 自定义 webpack DevServer 消息

javascript - 在不丢失结构的情况下过滤嵌套的树对象

javascript - webpack ://mean? 到底是做什么的

ruby-on-rails - Rails 6 - 如何在 js.erb 文件中包含 javascript_pack_tag

reactjs - 为什么我必须在 React 中使用 "require"而不是 "import from"作为图像?

webpack - 任何 Webpack splitchunks.name 作为网站以外的功能文档?