Angular4: Component.name doesn't work on production

后端 未结 4 1680
有刺的猬
有刺的猬 2021-01-03 10:42

So I\'ve been facing this weird issue but I\'m not sure if it\'s a bug or it\'s me missing something here.
So I have a component called TestComponent and in

相关标签:
4条回答
  • 2021-01-03 11:20

    I just answered a related question here

    To workaround mangling class names, you can create a function and check if it is equal to the class you want to test. In this case for TestComponent, you could use this:

    getType(o: any): string {
          if (o === TestComponent)
              return 'TestComponent';
    }
    

    And calling it will print the Component name:

    console.log(getType(TestComponent)); // will print 'TestComponent'
    
    0 讨论(0)
  • 2021-01-03 11:30

    Yes, this is normal since angular-cli/webpack and other tools are changing the class name by minifying the JavaScript code. So after minification in production build, you'll always only see one letter or something similar.

    Don't use this name in your logic because it will break in production.

    0 讨论(0)
  • 2021-01-03 11:35

    Function name contains actual function name. If the function is minified to one-letter name, it loses its original name. It should never be relied on in applications that can possibly be minified at some point i.e. every client-side application. There may be exceptions for Node.js.

    name is read-only in some browsers and and thus can't be overwritten. If a class needs identifier, it should be specified explicitly under different name:

    class Foo {
      static id = 'Foo';
      ...
    }
    

    Here is a related question.

    0 讨论(0)
  • 2021-01-03 11:37

    The best way I found was to use a library that renames the class at compile time, works similar to the C # nameof. nameof<MyInterface>(); Result: "MyInterface"

    https://github.com/dsherret/ts-nameof

    0 讨论(0)
提交回复
热议问题