I need to insert data-attr to react component at webpack compilation time. For example I have this component:
export const MyComponent = (props: any) => {
return (
<div>bla bla</div>
);
};
And after compilation I need this:
export const MyComponent = (props: any) => {
return (
<div data-attr="some data">bla bla</div>
);
};
I have wrote following plugin(which I think is almost complete, but I can not find a way to insert attribute):
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');
}
}
from Webpack custom plugin. Insert attribute in react component with AST
No comments:
Post a Comment