Skip to content
Discussion options

You must be logged in to vote

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!
      }
    });
  }
}

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@alexander-akait
Comment options

@mjames-c
Comment options

Answer selected by mjames-c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants