Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular / Typescript class.name does not work in production build

Using Angular 5. Facing a weird issue with class.name property. We have the following function in typescript:

export class ApiService
{
  public list<T>(c: new(values: Object)=> T)
  {
    var cname = c.name;
    ....
  }
}

Now, if I use this function in dev build of Angular (ng-build) like the following:

export class Employee()
{
    public id:string;
    public name: string;

    constructor(values: Object = {}) {          
       Object.assign(this, values);          
    }
}

And in code somewhere:

var list = api.list(Employee);

The above works, and in the list function I get cname = 'Employee'

However, if we build this solution using ng build --env=prod, the code fails and we get cname = undefined.

Why is this happening, and how to resolve it ? Shouldn't something that compiles and works in dev build, work in production ?

like image 902
user3395924 Avatar asked Feb 13 '18 03:02

user3395924


1 Answers

You are likely running into an issue with minification, which only occurs during a prod build. Minification will rename your classes in order achieve the smallest output file size.

See this question and answer for a related discussion: Angular-cli : How to ignore class names from being minified

As the answer above mentions, in order to configure this option, you will need ng eject your app, which will allow you customize UglifyJS options (the library responsible for minification), but this will also prevent you from using some of the nice features of the Angular CLI (like ng build and ng serve).

See this GitHub comment for a description of ng eject: https://github.com/angular/angular-cli/issues/6302#issuecomment-301220770

like image 53
Nathan Friend Avatar answered Oct 21 '22 19:10

Nathan Friend