0

I have a class with a custom toJSON implementation so that I can override the default serialization done by JSON.stringify.

When testing locally it works as expected but on production the custom toJSON method is not called:

class Foo {
  toJSON() {
    return "Hello World"
  }  
}

console.log(JSON.stringify({foo: new Foo()}));
// returns: { foo: "Hello World" } on local 
// returns: { foo: {} } on production

I am pretty sure this is happening because our production builds are handled by Angular CLI with the --prod flag enabled. This causes uglifyjs to kick in and rename toJSON to some cryptic value which ofcourse is not picked up by JSON.stringify.

Is it possible to tell Angular CLI to ignore special function names such as toJSON in the minfication/uglification process?

Liam
  • 27,717
  • 28
  • 128
  • 190
Swayam
  • 580
  • 6
  • 11
  • You say you're pretty sure, did you actually look for toJSON in the prod bundles? – jonrsharpe Mar 12 '20 at 08:15
  • 1
    You can ask the [terser plugin](https://github.com/webpack-contrib/terser-webpack-plugin) to don't minify class methods or just a specific class method. But this is useful only in rare case where the plugin does mistakes. In your case, instead, it looks like you are trying to use a class that wasn't exported globally. If you are trying to instantiate the class from the browser console, there are a lot of good reasons why it shouldn't work. Try instantiating it and calling the method inside an Angular component, and all the problems should have gone. – Christian Vincenzo Traina Mar 12 '20 at 08:21
  • (I was about to post it as an answer, but the question got closed in the while, I'm gonna vote for reopen it) – Christian Vincenzo Traina Mar 12 '20 at 08:22
  • @jonrsharpe yes I did. I searched for `toJson` in the local build and found it, but it was no where to be found in the production build – Swayam Mar 12 '20 at 08:22
  • @CristianTraìna thank you. I am doing all of this from within the context of an angular component. Is the terser plugin configurable via angular? Apologies if this is a stupid question, I am not very familiar with configuration of angular projects – Swayam Mar 12 '20 at 08:26
  • @Swayam If you are doing it within an angular context, then you shouldn't have problems, because both the method name and the method call get replaced with the same symbol. So you have the method (for example) `Obj.prototype.lk2` and the call to `obj.lk2()`. If you want to disable all the minifications, you can use `--build-optimizer=false`. Otherwise you can change the `TerserPlugin` config in your webpack extra – Christian Vincenzo Traina Mar 12 '20 at 09:27
  • 1
    You can also annotate a specific function call with `/*@__PURE__*/` – Christian Vincenzo Traina Mar 12 '20 at 09:27

0 Answers0