Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify nested properties

I'm using terser-js to minify my code.

The output:

a.prototype.a = ...
a.prototype.b = ...
a.prototype.c = ...

What I want:

var h = a.prototype
h.a = ...
h.b = ...
h.c = ...

Note that I can't write it by hand because the inputs are generated from TypeScript.

like image 382
W.H Avatar asked Dec 20 '18 04:12

W.H


1 Answers

terser-js does not appear to have such a feature, and it actually makes sense that it wouldn't. Those two pieces of code can actually behave differently (getter properties can return different values on each access) and the resulting code would actually be larger in most use cases.

I know the first example looks larger, and uncompressed it is, but once compressed with something like gzip (if you care about file sizes, you better be using using gzip, as most servers do) that repeated data is easily compressed into the compression dictionary, and the resulting compressed data is actually smaller than if the object was aliased.

Some minifiers actually used to support various features similar to what you are describing (Closure Compiler in particular), but the developers later realized it was actually counter-productive and removed such features.

To illustrate this behavior, I've created these 2 files:

a.js :

a.prototype.a = 'testing 1';
a.prototype.b = 'testing 2';
a.prototype.c = 'testing 3';

b.js :

var h = a.prototype;
h.a = 'testing 1';
h.b = 'testing 2';
h.c = 'testing 3';

Check out the results after I compress them with gzip:

$ gzip -k -9 *.js
$ ls -l
total 32
-rw-r--r--  1 user  group  87 Dec 22 15:50 a.js
-rw-r--r--  1 user  group  69 Dec 22 15:50 a.js.gz
-rw-r--r--  1 user  group  78 Dec 22 15:50 b.js
-rw-r--r--  1 user  group  75 Dec 22 15:50 b.js.gz

The a.js.gz file is actually the smallest file.

like image 141
Alexander O'Mara Avatar answered Oct 26 '22 22:10

Alexander O'Mara