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:
a
s, I have to rename all the variables haha
to hehe
in all modules in the chunk of the said entry point.a
s, I have to rename all the variables haha
to hoho
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?
I opened an issue. Response from Tobias Koppers:
That's not possible.
The modules are independent from the original entrypoint. The module graph doesn't contain this information. In addition to that modules can be in both entrypoints, but are not build twice in this case.