What is the best way to share state between Webpack plugins for a compilation lifecycle? #19976
-
I have some state that needs to be shared between Webpack plugins that only needs to persist for a compilation lifecycle. One approach for doing this is to mutate the class PluginA {
apply(compiler) {
compiler.hooks.compilation.tap('PluginA', (compilation) => {
compilation.pluginAState = { message: 'Hello from Plugin A!' };
});
}
}
class PluginB {
apply(compiler) {
compiler.hooks.compilation.tap('PluginB', (compilation) => {
if (compilation.pluginAState) {
console.log(compilation.pluginAState.message); // Output: Hello from Plugin A!
}
});
}
} Is this the recommended approach for sharing state? If not what is it? |
Beta Was this translation helpful? Give feedback.
Answered by
xiaoxiaojx
Oct 3, 2025
Replies: 1 comment 2 replies
-
A common way to share state between Webpack plugins for a compilation lifecycle is to use a WeakMap keyed by the compilation. const stateMap = new WeakMap();
class PluginA {
apply(compiler) {
compiler.hooks.compilation.tap('PluginA', (compilation) => {
stateMap.set(compilation, { message: 'Hello from Plugin A!' });
});
}
}
class PluginB {
apply(compiler) {
compiler.hooks.compilation.tap('PluginB', (compilation) => {
const state = stateMap.get(compilation);
if (state) {
console.log(state.message); // Hello from Plugin A!
}
});
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
mjames-c
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A common way to share state between Webpack plugins for a compilation lifecycle is to use a WeakMap keyed by the compilation.