Skip to content

keepNames with static class fields and initialization blocks #2389

Closed
@esdmr

Description

Static fields and initialization blocks in classes run before the name of the class is set. If the static part is referencing the name of the class, it fails in certain cases.

  • If I do not specify either bundle or format, esbuild does not rename the classes, and therefore the bug does not occur.
  • If I specify bundle, esbuild sets the static class fields after the name, but keeps the static initialization blocks in the class.
  • If I only specify format, esbuild keeps both static parts in the class just before setting the name.
class DirectlyReferenced {
    static type = DirectlyReferenced.name;
}

console.assert(DirectlyReferenced.type === 'DirectlyReferenced', 1);

class ReferencedViaThis {
    static type = this.name;
}

console.assert(ReferencedViaThis.type === 'ReferencedViaThis', 2);

class StaticBlock {
    static {
        console.assert(this.name === 'StaticBlock', 3);

        // StaticBlock is undefined here with --bundle.
        console.assert(StaticBlock?.name === 'StaticBlock', 4);
    }
}

I suggest moving the function call that sets the name like so:

class Data {
    static {
        setName(Data, 'Data');
    }

    static type = this.name;

    // ...
}

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions