Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Potential failure in static initializer when bundling #3025

Closed
pfumagalli opened this issue Mar 28, 2023 · 1 comment
Closed

Potential failure in static initializer when bundling #3025

pfumagalli opened this issue Mar 28, 2023 · 1 comment
Labels

Comments

@pfumagalli
Copy link

pfumagalli commented Mar 28, 2023

When bundling is enabled, class definitions are rewritten as variable assignment + anonymous class, and that might create some issues with static initializers.

For example, given this code in testme.js:

export class MyTest {
  static {
    MyTest.prototype.foo = 'bar'
  }
}

When not bundling (e.g. esbuild --format="esm" testme.js, the code gets transpiled as follows:

class MyTest {
  static {
    MyTest.prototype.foo = "bar";
  }
}
export {
  MyTest
};

In this case the static initializer works without any issues. On the other hand, when bundling (e.g. esbuild --format="esm" --bundle testme.js) the class definition gets rewritten this way:

// testme.js
var MyTest = class {
  static {
    MyTest.prototype.foo = "bar";
  }
};
export {
  MyTest
};

In this second case, the static initializer fails as MyTest is not defined when running the static initializer.

I think that preserving the class name in the variable assignment should be "ok" (there doesn't seem to be any side effect), and this seems to work (OtherTest is defined, MyTest is not):

var OtherTest = class MyTest {
  static {
    MyTest.prototype.foo = 'bar'
  }
}

// ... here `MyTest` is not defined...

export {
  OtherTest
}

But I'm not 100% sure whether this would be a good solution or there might be some alternatives...

Note, yes, I know we can use this to refer to the class in the static initializer, but I don't have control over the library's source, unfortunately!

pfumagalli added a commit to juitnow/justus that referenced this issue Mar 28, 2023
@evanw evanw added the classes label Apr 2, 2023
@modderme123
Copy link

I just ran into a similar issue with @angular/core as well, and noticed that this is probably a duplicate of #2950

@evanw evanw closed this as completed in c12cc90 Jun 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants