Webpack 5 memory leak in watch mode

Bug report

What is the current behavior?
When I make a change in my web app and Webpack compiles, memory usage seems to increase. If I keep making changes and Webpack keeps re-compiling, memory usage will continue to climb. In a large project I work in, it takes about 10 compilations until Webpack crashes with a “Allocation failed – JavaScript heap out of memory” exception.

If the current behavior is a bug, please provide the steps to reproduce.
Please see the minimal repo I created to reproduce the issue: https://github.com/Geksanit/wp5-memory-leak.
1 yarn start
2 save any ts/tsx files without changes

What is the expected behavior?
I would expect some kind of garbage collection to happen in between compilations.

Other relevant information:
webpack version: 5.24.1
Node.js version: 12.19.0
Operating System: Win10
Additional tools: yarn 1.22.10

1 possible answer(s) on “Webpack 5 memory leak in watch mode

  1. Ok I looked into that a bit deeper and there is a pretty serious memory leak that happens when removing modules from the compilation. e. g. removing an import.
    But it’s not that easy to fix.

    One problem are backward-compat back references to objects one should not have access too. That’s easy to fix by removing the backward-compat references when the next Compilation starts. In the next major they will be removed anyway.

    Another problem is that modules in cache keep referencing the Compilation they were created in (indirectly e. g. through the parser), which then references a lot other objects. We need to move such references (like parser, generator, etc) from the Module to the ModuleGraph and give the Module access to the ModuleGraph at places where it want to access it’s references. And to make it backward-compatible we need to add a lot getters for the old references.