Skip to content

Memory leak when running with multiple webpack (compiler) instances #1203

@valerio

Description

@valerio

Expected Behaviour

When creating and disposing multiple webpack instances using ts-loader, compiler instances should not be retained.

Actual Behaviour

When running a build with ts-loader, webpack compiler instances are never removed by the GC.

Steps to Reproduce the Problem

  1. create a minimal ts-loader configuration like the one from the readme
  2. create a webpack compiler and call run() on it without storing any references
  3. repeat step 2 enough times and the node process will run out of memory

Location of a Minimal Repository that Demonstrates the Issue.

https://github.com/valerio/ts-loader-leak

Additional details

I have an application that runs webpack in-memory to transpile some TypeScript code.
The webpack compilers are disposed after some time, but I noticed that references to them were still being held by ts-loader.

I've spent some time debugging this and I saw that these references are held by the webpackInstances array:
Screenshot 2020-10-31 at 13 42 33

The array is declared here: https://github.com/TypeStrong/ts-loader/blob/master/src/index.ts#L30
This is a global variable and references are only ever added to it, never removed, as far as I can see.

The array is used to determine a key for an instance cache, which is using a WeakMap: https://github.com/TypeStrong/ts-loader/blob/master/src/index.ts#L189-L196

I think this array could be replaced with another WeakMap itself (or use WeakRef) so it doesn't retain compiler instances.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions