Problem
Hi, I'm trying to write a plugin and use ast for parsing the file. But I can not make changes to code. For example this code does not change div to label. What is correct way to change ast?
apply(compiler) {
compiler.hooks.normalModuleFactory.tap('MyPlugin', (factory) => {
factory.hooks.parser.for('javascript/auto').tap('MyPlugin', (parser, options) => {
parser.hooks.program.tap('MyPlugin', (ast, comments) => {
if (parser.state &&
parser.state.module &&
parser.state.module.resource.indexOf('node_modules') === -1) {
if (parser.state.module.resource.endsWith('tsx')) {
var g = ast.body.filter(n=> n.type === 'ExportNamedDeclaration');
for (let a of g) {
var decl = a.declaration.declarations;
if (decl && decl[0]) {
decl[0].init.body.body[0].argument.arguments[0].raw = 'label';
decl[0].init.body.body[0].argument.arguments[0].value = 'label';
}
}
}
}
});
});
});
}`
I just need to change div to label in return block or add data-attr to div. I do not want to use regular expressions and replace all file content, I want to make it with ast. MyComponent.tsx can be as following:
import * as React from 'react';
import * as style from './MyComponent.css';
export const MyComponent = (props) => {
return (
<div className={style['test']}>bla bla</div>
);
};
May be somebody can provide small example to change something with abstract syntax tree in webpack plugin.