Skip to content

"Cannot access '_A' before initialization" when using static properties and a static initializer #13500

@usefulthink

Description

@usefulthink

Describe the bug

When using both a static initializer block and static properties in a typescript class A, the compiled result produces an error: Uncaught ReferenceError: Cannot access '_A' before initialization.

This is the class in question:

export class A {
  static MAP = new Map();

  static {
    Object.defineProperty(this.prototype, 'foo', { value: 123 });
  }
}

And vite compiles this to:

const _A = class {
  static {
    Object.defineProperty(_A.prototype, "foo", { value: 123 });
  }
};
export let A = _A;
A.MAP = /* @__PURE__ */ new Map();

Now this may very well be an upstream problem, but I wasn't able to figure out where it is caused. It seems that esbuild (with what little I understand of it) will produce correct results, either by compiling the static initializer into an IIFE (target es2020) or by keeping both constructs as they are (target esnext).

Maybe someone here can point me into the right direction? Maybe there's even a way to get this to work without having to wait for upstream fixes to land?

Reproduction

https://stackblitz.com/edit/vitejs-vite-xghabj?file=a.ts

Steps to reproduce

No response

System Info

System:
    OS: macOS 12.6.5
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 28.48 MB / 32.00 GB
    Shell: 5.2.15 - /usr/local/bin/bash
  Binaries:
    Node: 18.16.0 - ~/.nvm/versions/node/v18.16.0/bin/node
    npm: 9.5.1 - ~/.nvm/versions/node/v18.16.0/bin/npm
  Browsers:
    Chrome: 114.0.5735.106
    Chrome Canary: 116.0.5828.0
    Firefox: 108.0.2
    Firefox Developer Edition: 110.0
    Safari: 16.4.1
  npmPackages:
    vite: ^4.2.0 => 4.3.9

Used Package Manager

npm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug: upstreamBug in a dependency of Vite

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions