Suggestion: minification
TypeScript should support emitting minified JavaScript.
There are several different things we could support:
- Just remove whitespace
- Minify unobservable identifiers
- Remove provably dead code
- Whole-program minification (i.e. closure compiler)
- (Others?)
Meta: Is this the canonical issue tracking the proposal to create a path to an optimizing backend (be it built-in or via Closure annotations)? It appears to be at a glance, but if I'm missing a more appropriate spot, I'd appreciate a pointer to it.
I'd just like to throw in my 2¢ in support of an optimizing backend. My company's using Typescript very heavily, and while using Closure's basic optimization mode on the output helps to a certain extent, it's quite obvious that we can do a lot better. Code size may not matter to everyone, but it should -- it's not just about over-the-wire size, which is (mostly) mitigated by gzip, but about memory use, parse time, and runtime performance (yes, you can still achieve significant improvement through static optimization). There's a reason that Google invested heavily in optimization for both the Closure and GWT stacks (full disclosure -- I worked a lot on GWT and to a limited extent on Closure when I was there).
Just to be clear, this is what I mean when I suggest that we can do a lot better than just dropping whitespace and obfuscating local identifiers:
function rAb(a,b){if(!b.ib.a){Sae(a.a.a.a.a.d,(Klf(),new Nwf(b)));bOe(a.a.a.a.a.i,a.a.a.a.a.i.c)}}
function Cqb(a,b){a.f=b;if(!b.yb){a.a.we(new Aqb(a.b,a.f,null));return}wqb(a.d,b.Fb,new Iqb(a))}
function Bqb(a,b){var c;a.b=b;c=b.g;if(c.fh()){Cqb(a,b);return}vae(a.c,c.Br(0).Fb,false,new bbe(new Gqb(a)))}
function Pfd(a,b,c){var d;d=new Ufd(a);Bgd(a.a,d);Agd(a.a,b,c);dgd(a.b,new Wfd(a));Jpb(a.b,new Yfd(a));Qfd(a)}
function Ppd(a){var b;b=new qid(Dte(AFd(a.a)),bue(AFd(a.a)),aue(AFd(a.a)),Opd(a),knc(XEd(a.a)));return b}
function $pd(a){var b;b=new kmd(NXf(QFd(a.a)),(new rnd,KFd(a.a),new ndf),new hid(pKc($Ed(a.a))));return b}
function Rnd(a){var b;Sgf(a.s);if(a.o.S){return null}b=a.U.vg();return !!kfi(b).length&&!u_(b)?b:null}
function Pnd(a){Sgf(a.s);if(a.o.S){return nt(),mt}if(a.N.e.f.a){return nt(),mt}else{Sgf(a.M.e.f.a);return nt(),kt}}
function Gld(a){if(!a.j||!ZM(a.d.b,(Jw(),Qv))){return scf((Yci(),Yci(),Wci))}return icf(a.n,new Jld)}
function Mkd(a){a.a.wk((RJf(),KJf));wbb(a.a,eui);a.a.Oe(true);Fbb(a.a,new Ukd(a),BRf?BRf:(BRf=new wQf))}
function Jhd(a,b){var c,d;d=Bae(a.c,b);c=Lld(Ypd(a.a.a),b,d);return Nhd(new Ohd(a),(Ngf(c.d),new Ild(c,true)))}
The above is a random chunk of GWT output from a Google app. The details don't matter -- the point being that aggressive optimization can dramatically reduce output size, make a non-trivial difference in parse time and runtime performance, and even amplify gzip compression by allocating identifiers in such a way as to reduce input entropy.
As has been pointed out earlier on this thread, there are two obvious routes we can take:
- Build an optimizing backend into tsc.
- Add an option for generating Closure jsdoc annotations.
I don't have a strong preference -- as long as it's possible to get good output, I don't care much how we get there. The output example above came from the GWT compiler, but Closure achieves similar results. Michael Bolin (who did a lot of the work on Closure at Google) created a proof-of-concept (http://bolinfest.com/typescript/) a couple of years ago, but didn't take it much further than that. It's not an entirely trivial exercise, because of the impedance mismatch between Typescript and Closure's inheritance mechanism in particular, but it doesn't seem like brain surgery either.
The hardest design problem, as I see it, is dealing with exposed vs. optimizable symbols. Closure has annotations for dealing with "exporting" symbols, and Typescript would need something similar to make the optimizer useful. There are also important edge cases like dealing with externally defined objects (both importing third-party libraries, and dealing with the output of APIs like JSON.parse). The compiler must know about these things if it is to avoid breaking the output with an aggressive optimizer.
I think it would be fairly easy to rally a few people to work on an optimizing backend for Typescript, but only if the team is bought into the idea. Trying to bolt such a thing onto the existing compiler, without the ability to tweak the compiler and language a bit, is probably a fool's errand. So I'd greatly appreciate any indication from the team as to their disposition on the subject.
I really like the "random chunk of GWT output from a Google app". In addition to the benefits mentioned above, another objective is protection of intellectual property through obfuscation. If anybody has tried stepping through the code in Google Maps then they will know the protection that aggressive minification can provide in this regard.
The annotation (for excluding minificaton) is not only relevant for externally defined objects, but also relevant when properties of JavaScript objects are bound to elements in the HTML.
I decided not to say anything about obfuscation for the purpose of, well... "obfuscation", at least partially because I know that tends to raise a lot of hackles in the web world :) A bit more seriously, I'm less concerned about it simply because I've spent so much time reverse-engineering highly-obfuscated Javascript (e.g., http://www.j15r.com/blog/2005/02/09/Mapping_Google) that obfuscation only feels like a speed bump. But hey, a big speed bump can still be useful.
Regarding annotation, right -- I forgot to mention that runtime-provided types are equivalent to external code. The (small, but important) distinction being that you tend to have relatively stable and available IDL for the former, whereas the latter's a bit of the wild west. If you have type information (e.g., via DefinitelyTyped), you're good to go, but if not you have a problem. Personally, I'd be fine with requiring explicit type information for all external libraries as a precondition for aggressive optimization, but I'm not sure that's a majority opinion.
FWIW, Closure basically takes that approach. If you don't have type annotations for external code, Turing only knows what it will do under advanced optimization (actually, I don't even think Turing knows, because it's probably undecidable, and the compiler certainly can't tell you). With GWT it was a bit easier, because you needed explicit (lightweight, optimized away) Java interface wrappers to call into Javascript in the first place. So the compiler only has an aggressive mode, because it can prove that the output won't be broken (as long as your Javascript methods don't "cheat").
Requiring explicit types also works for dealing with parsed JSON (our rather large body of Typescript uses interfaces for all parsed values; otherwise we'd be breaking things left and right). I believe Closure allows for this, but the traditional method was to require string accessor syntax for any properties that weren't defined by the compiler (e.g., value = parsedThing["someField"]). This is a pretty foul hack that I believe goes unchecked by the compiler, though, and I wouldn't be in favor of doing anything that nasty in Typescript. After all, that's one of the great benefits of making interface definitions an order-of-magnitude less verbose than in Closure.
@joelgwebber that is a really great appeal.
Just wondering: with variables and modules/classes and their members being necessarily declared, can't the optimizer ONLY rename members which are traceable back to a declaration? An any or an any which is known to implement an interface is still external code and those identifiers are not declared. (And declare declarations don't count.)
But in code with multiple namespaces, we would be forced to export too many items - items which are needed within the application by different namespaces, but not outside of it. So there'd need to be some additional level of accessibility between non-export and export, like internal?
Don't forget there should be available an option in Visual Studio --> Config Transform (transformation) for Web.Config that are tied in to Visual Studio's Configuration Manager. That way we as developers should not be seeing minified javascript during development, especially when there's error or when debugging javascript source code.
I know this is about TypeScript minification thing but when in Visual Studio runtime via F5 key, it compile TypeScript to Javascript & I wouldn't want to see minified Javascript code during developing. Also, the Config Transform are tied in to publisher too. I would rather have minified javascript code when publishing to production sever but not minified to developer server.
Just saying.
@Gitgiddy : I believe that's correct. The compiler can't go renaming symbols whose provenance are not known, and which it can't prove haven't "escaped" into any references or external code. In a language like Typescript, this requires global type inference. I know the compiler does a certain amount of type inference already, but I don't know how broadly scoped it is -- if it's just for locals, that could prove problematic.
@fletchsod-developer: Of course. We'd be nuts to run an optimizing backend with global type inference on every compile. You really only want that before deploying to production.
I really would love to see this issue moved forward. It's evident that this is something people want (few users of Typescript would object, I'd challenge anyone to find a die hard objector). The issue is, it needs to be implemented correctly.
@Gitgiddy, I think you're absolutely right about the need to declare modules as internal vs external. But to add a keyword to the language for the sole purpose of minification isn't compelling. Private, protected, public - all of these keywords are very helpful to us for purposes other than minification, though they're incredibly helpful for that purpose.
With the merger of Typescript and AtScript, we finally have a syntax that's endorsed for data annotations. Is there a roadmap for specifying which annotations can be picked up by the compiler, I wonder? I'm sure that's something that's wanted by many people, so I'll assume that's avenue to pursue on a configuration level.
What if we were to steer this thread to a conversation about some standards which could be implanted, should minification be a feature of the compiler?
To start -
- is it safe to assume anyone desiring a higher level of minification than UglifyJS will be willing to put the work into their codebase, as to not use implicit any, and have every piece of data defined by an interface?
- Is there a real objection to NOT minifying private and protected members?
- Can annotations be used to provide directives to the minifier?
Solving these questions would be a good start. I feel that there could be more taken though:
- If annotations cannot be used on Enums, interfaces, or modules (as I don't see that in the AtScript syntax) how can we provide information about the intended minification level for these features? Can the annotation system be extended to work on things other than classes?
Don't get distracted by the last point there. Let's start with the first three? I feel like there could be some progress on something if a common consensus began to emerge.
Perhaps with Ron Logan's (aka ronlo http://ajaxmin.codeplex.com/team/view) expertise, the development of this feature can elevate? He has done tremendous work in JavaScript minification over the past several years.
I think main selling point for dead code elimination is util libraries like lodash/underscore. TypeScript would become immediately much better for compiling those, than e.g. modularity of lodash which requires programmer to keep the mini-packages updated.
I think this is a must have for TypeScript. It's a great language and gaining a lot of support, especially with the Angular 2.0 stuff. Now that I have developed a lot of TypeScript code and almost ready to deploy I now wish I hadn't used such long and descriptive naming (which I always do). Unfortunately, I thought they would minify OK. I tried using Closure but it broke more than it helped.
Coming from C# background I think annotations are the way to go. But they should be "opt out" instead of "opt in" for class properties and methods (both private and public), therefore they are minified by default.
Is there a way to elevate this so that someone on the TS team can at least tell us if it is being considered in the near future?
Until then I'm going to try to roll something on my own (which will probably leave me bruised).
Is there a way to elevate this so that someone on the TS team can at least tell us if it is being considered in the near future?
Minification has always been one of our most requested features, and one that we have talked about on and off throughout the past few years. It is a substantial amount of work though, assuming you are not just looking for white space removal, and variable name shortening. Moreover, minification has existed in JavaScript tooling for a long time, and there are already multiple minifiers that plug into existing JS workflows. We have been really busy with ES6 and other language/tooling features for TypeScript which made us shy from taking on such a big problem; specially that TypeScript compiles to JavaScript which allows you to leverage any existing JS tools out there. That said, it is not that we are ignoring the issue; it is still open because we believe that there is problem out there that TypeScript can help solve.
@mhegazy, thanks a lot for the reply. I'm sure you're very busy and I wasn't trying to push! I just wanted to know if anything was on the near term radar. Good luck with the ES6 stuff. TypeScript is great.
I second @jasonwilliams200OK's suggestion regarding Ron Logan. They have a well-maintained minifier (that I have used in the past) that could possibly be adapted to work for TypeScript. I have found Ron very proactive on the subject.
We are currently doing some JSDoc infrastructure work including parsing and AST representation, once that is done, generating type-annotated JSDoc comments should be fairly easy and will unblock more minification/optimization scenarios. We would be open to taking a PR for that.
Would like to see TypeScript compiler to support advanced minification feature!
So far, I have to create the externs file by myself and use the bracket notion to export the symbols.
For now, I am trying to generate the extern files from the .d.ts type file (aforementioned as Option B by @NoelAbrahams) by using typescript compiler APIs, so I don't need to manually change the externs file every time I use a new external API.
Why has this issue been closed?
@antoinerousseau, this issue is not closed :question::grey_exclamation:
oops yes sorry I got confused with the Closed label next to the #3503 reference just above
@mhegazy, you mentioned that it would be difficult to do, assuming that you weren't just looking for white space removal, and variable name shortening.
In my opinion, it is the second item in your list which would be the most beneficial. In our pipeline, we use UglifyJS to handle minification of TypeScript output, and it handles the AST optimization pretty well. What it can't handle, that Typescript can handle, is the second item you listed as a simpler task (variable name shortening.)
How could someone get more involved in that area of the project? Introducing variable name shortening as an option, would in my opinion be a huge piece of the pie, as that's the area where type definitions are required the most.
@bryanerayner we are currently looking into updating the implementation the emitter to allow for a transformation pipeline. no ETA at the point, but when this happens emitter changes should be much simpler to do.
I worry that a set of options to partially minify will not solve the original issue, but will introduce new complexities for users and in the code base. if this is something that you find interesting, feel free to look at the compiler sources and the API, and provide a proposal for how you intend it to work.