Recently, I started learning how to build webpack plugins. I'm trying to build a plugin that will update my source code.
The rules are simple:
- If the entry point name has less than 2
a
s, I have to rename all the variableshaha
tohehe
in all modules in the chunk of the said entry point. - If the entry point name has more than 2
a
s, I have to rename all the variableshaha
tohoho
of all modules in the chunk of the said entry point.
This is my code:
a.js
const haha = 'hello';
// will be "const hehe = 'hello';" in the bundle of "aa" entry point
// will be "const hoho = 'hello';" in the bundle of "aaaa" entry point
console.log(haha);
// will be "console.log(hehe);" in the bundle of "aa" entry point
// will be "console.log(hoho);" in the bundle of "aaaa" entry point
export default haha;
// will be "export default hehe;" in the bundle of "aa" entry point
// will be "export default hoho;" in the bundle of "aaaa" entry point
few.js
import haha from 'a'; // will be "import hehe from 'a';" in the bundle
console.log(haha); // will be "console.log(hehe);" in the bundle
lots.js
import haha from 'a'; // will be "import hoho from 'a';" in the bundle
console.log(haha); // will be "console.log(hoho);" in the bundle
webpack.config.js
module.exports = {
mode: 'development',
entry: {
aa: 'few.js',
aaaa: 'lots.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
};
I don't know exactly what the proper way to do that.
At the beginning, I thought that my plugin has to register to a specific hook of the parser, check the name of the current entry point and replace the name of the AST node. The problem is that the module a.js
is parsed only once.
The second way I tried is to register to the render
hook of the mainTemplate
and rename variables via a simple regex. I don't like this method since code replacing via regex is extremely difficult (IMO).
What do you think? What is the proper way to that?