andreypopp / autobind-decorator

Decorator to automatically bind methods to class instances
MIT License
1.45k stars 66 forks source link

boundMethod decorator might not be usable in Angular production builds #82

Open jeffmath opened 5 years ago

jeffmath commented 5 years ago

I get this error when running production builds of my Angular app, which contains usages of the boundMethod decorator:

 Error encountered resolving symbol values statically. Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler (position 3:22 in the original .ts file), resolving symbol boundMethod in C:/Users/Jeff/[path to my app]/node_modules/autobind-decorator/index.d.ts

I believe it is the Angular AoT compiler which is throwing this error. Devleopment builds, which don't use AoT, don't produce these errors.

I import the decorator using import { boundMethod } from "autobind-decorator";

A workaround is to use the autobind decorator instead, though that is discouraged by this package's docs.

jeffmath commented 5 years ago

Another workaround is to change index.d.ts to make boundMethod the default export, as in:

export declare const autobind: ClassDecorator & MethodDecorator;

declare const boundMethod: MethodDecorator;
export declare const boundClass: ClassDecorator;

export default boundMethod;

With this, of course, using the autobind decorator would result in a production-build compile error similar to the one described above.

stevemao commented 5 years ago

Is it a typescript issue? If so I don't use it so help is needed.

In essence, we should always do import { boundMethod } from "autobind-decorator";, keeping the other two exports are mainly for backwards compatibility.

jeffmath commented 5 years ago

I'm sorry - yes, it is a TypeScript issue. Most everyone who uses Angular 2+ uses TypeScript for their coding.

To be able to do as you have prescribed, a person would have to employ the second workaround I've given, above.. I don't know if you want to incorporate that change into the package, or not. It makes boundMethod the default export.

stevemao commented 5 years ago

I think (I might not be correct since I don't use typescript) the problem is since boundMethod is the recommended way, it should be the default export. Well it's just one of the three exports we have here and default export doesn't imply the importance. We do it this way purely for backwards compatibility. I doubt it's worth the effort to make a breaking change just for typing...

jeffmath commented 5 years ago

@stevemao That is understandable. I guess I will have to continue using my fork with the workaround in it.