【发布时间】:2019-09-19 12:40:35
【问题描述】:
我需要在 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 编写过插件,但我目前正在努力配置它们,这就是我偶然发现你的问题的原因。
标签: javascript webpack webpack-4 webpack-plugin