TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: minification

Open RyanCavanaugh opened this issue 12 years ago • 193 comments

TypeScript should support emitting minified JavaScript.

There are several different things we could support:

  1. Just remove whitespace
  2. Minify unobservable identifiers
  3. Remove provably dead code
  4. Whole-program minification (i.e. closure compiler)
  5. (Others?)

RyanCavanaugh avatar Jul 15 '14 16:07 RyanCavanaugh

but, don't you want publicMethod not to be mangled?

eggers avatar Dec 29 '15 07:12 eggers

@eggers, then you use an additional switch --mangle-regex="/Private/". As a library author, if you are using some convention like underscrore before/after the private properties names, then this option is for you.

ghost avatar Dec 29 '15 08:12 ghost

Which is why it is best left to tools that are designed to minify. While TypeScript might have more context, there has been a lot put into the minfication tools to make them work in the myriad of use cases. The only improvement I can really see is that it "intelligent" minification is built into a build pipeline that utilises the language services of tsc to provide some guidance. Integrating that directly into TypeScript though seems to be an anti-design goal:

  1. Provide an end-to-end build pipeline. Instead, make the system extensible so that external tools can use the compiler for more complex build workflows.

as well as:

  1. Aggressively optimize the runtime performance of programs. Instead, emit idiomatic JavaScript code that plays well with the performance characteristics of runtime platforms.

Which is why I guess I am still surprised @RyanCavanaugh is suggesting it.

kitsonk avatar Dec 29 '15 09:12 kitsonk

@kitsonk, I agree.

postcss is an AST for CSS. Any CSS utility (compiler, compressor, linter) which implements postcss gives the free advantage of integrating all the other utilities built on top of postcss via piping. This integration is not "just" pipe contract either; they can share the context (the actual AST!) with each other.

I wonder if there is any general purpose AST built for JavaScript, which TypeScript, CoffeeScript, Uglify, SweetJS, LiveScript, JSHint, JSCS etc. can get compliant with to be able to "share the context" with each other and yet provide legendary experience -- as opposed to each implementing redundant features in different ways which BTW also goes against the DRY and single responsibility principles.

ghost avatar Dec 29 '15 09:12 ghost

Unfortunately, this discussion has been sidetracked by spurious arguments (by those, I suspect, not really familiar with real-world minification problems).

As I said above

uglify cannot [minify private methods] _(without further annotation)_

Without asking owners of code-bases spanning tens of thousands of LOC to carry out special annotation, there is _no tool in the present evironment_ that can effectively minify _TypeScript generated_ code.

A number of real-world problems have been discussed above, such as dealing with properties that are bound to the DOM (which shouldn't be minified). TypeScript can make a difference here. Please do take the time to read through the comments.

We are at present facing a script that is approaching many hundreds of KB and this feature suggestion remains critical for us.

NoelAbrahams avatar Dec 29 '15 09:12 NoelAbrahams

I am well familiar with real-world minification problems. I am simply explaining what is possible with Uglify today.

Please do take the time to read through the comments.

Have you read mine? I am not against this proposal.

Please speak for yourself only and don't be sarcastic. So we are sharing thoughts here and this conversation is well on topic (Uglify is relevant).

ghost avatar Dec 29 '15 10:12 ghost

@jasonwilliams200OK, sorry, no offence intended. I do urge you to stop making impractical suggestions, though :smile:.

NoelAbrahams avatar Dec 29 '15 10:12 NoelAbrahams

Unfortunately, this discussion has been sidetracked by spurious arguments (by those, I suspect, not really familiar with real-world minification problems).

That was a bit rude and uncalled for, and rather ill-informed.

I am very familiar with real-world minification challenges. Also you stated:

It is therefore likely that many library developers are put off from using TypeScript because of these inefficiencies.

I can tell you, as a CTO of a major company behind one of the largest open source JavaScript libraries hasn't dissuaded us from TypeScript. Maybe you should do a bit of research before you toss out throw away comments like that.

You originally stated:

uglify will not minify private methods.

@jasonwilliams200OK indicated that you could, providing a working example, which you dismiss out of hand. How does that become?

I do urge you to stop making impractical suggestions, though

Even with a smiley, that is uncalled for...

kitsonk avatar Dec 29 '15 11:12 kitsonk

Congratulations on your job.

The first suggestion was impractical, because it also minifies public methods. The second suggestion is intrusive, because it involves annotating private methods and/or following some sort of convention, such as an underscore prefix.

NoelAbrahams avatar Dec 29 '15 11:12 NoelAbrahams

You are seeing it as intrusive, I take it as room for improvement in Uglify, on which many users rely today. Turned out I am not alone as I have found this: https://github.com/mishoo/UglifyJS2/issues/103. See the comments by @jrhite. It is possible to control what properties to mangle in uglify today with programmatic usage, though further improvements might be required as the issue is still opened. TypeScript team can still take dependency on UglfiyJS in implementing this feature by injecting the context and controlling the internal steps.

Like i mentioned earlier, if TypeScript support some common AST core with foreign interface like postcss provides for CSS (so you can plug/swap minifier of your choice or any utility) and LLVM provides for native langs, then these features can be provided more effectively in a modular and extensible manner.

Please do implement this feature, preferably by engaging Uglify.

To sum up, we can achieve the same goal with one of the following approaches:

  • Take hard dependency on Uglify and package it with typescript. Less flexible, simplest to implement and simple to use.
  • Provide consumer to control annotation in generated code so they can make choice on taking dependency on Uglify or something else. Conversely, typescript to always annotate the private methods with fixed symbol. Flexible enough, simple to implement and use.
  • Be the first to provide intermediate AST core tier for convergence such as postcss. Very flexible and extensible, hard part is to convince everyone to converge to a common interface.
  • Implement the minification feature from scratch. This will take couple of iterations to become as good as Uglify, but eventually it will work too.

@NoelAbrahams, no problem. Same goal, different approaches. Like i said earlier, we are sharing thoughts and I provided information on what can be achieved today. Final decision on how will come from TypeScript team.

ghost avatar Dec 29 '15 12:12 ghost

@jasonwilliams200OK - I have no skin in this, but just an update. mishoo/UglifyJS2#103 should be closed as full support is already there. Additionally, another feature was added which allows very useful control over which properties do and don't get mangled. Check the uglify2 docs for more info.

--mangle-regex Only mangle property names matching the regex

Cheers!

jrhite avatar Dec 29 '15 13:12 jrhite

I know everyone's looking for the best direction for the project, so let's keep that in mind and try to keep the discussion civil and driven by the issue at hand.

DanielRosenwasser avatar Dec 29 '15 15:12 DanielRosenwasser

@jasonwilliams200OK,

I think your suggestion of TypeScript producing JavaScript output annotated in a language that Uglify (and perhaps other minifiers) can understand is probably the easiest route forward at present. This would work for us as we already use Uglify for our minification.

NoelAbrahams avatar Dec 29 '15 20:12 NoelAbrahams

Which is why I guess I am still surprised @RyanCavanaugh is suggesting it.

@kitsonk TypeScript issues 1 through 22 were manually ported by me from the old CodePlex site based on number of votes they had at the time. I don't really remember why we picked that number.

Honestly for all the comments that have been logged here, I'm shocked that there doesn't seem be be a reference implementation based on some very straightforward usage of the language service.

RyanCavanaugh avatar Dec 29 '15 23:12 RyanCavanaugh

@RyanCavanaugh,

Honestly for all the comments that have been logged here, I'm shocked that there doesn't seem be be a reference implementation based on some very straightforward usage of the language service.

If the TypeScript team is not going to implement this feature then I suggest this issue be closed. That may motivate someone to take this up. It would also help us in the decision to consider looking for alternatives.

This was one of the earliest issues raised (7th of October 2012 - just a few days after TypeScript went public), received a large number of votes before being moved to GitHub (6th in terms of number of votes), and three years later there has been no resolution.

NoelAbrahams avatar Jan 01 '16 14:01 NoelAbrahams

We haven't ruled it out. If someone has waited three years without looking for an alternative, they apparently don't need minification all that badly and I'm inclined to not proceed with it.

This has been sitting in "Needs Proposal" because, as I've outlined here many times, we're looking for someone to present a compelling case that TypeScript itself can do a substantially better job than off-the-shelf minifiers, in a way that is general-purpose enough to work for most people.

Our current belief is that this might be possible, but is almost certainly a huge amount of work that we could spend in more productive ways. I don't think it would be a great trade-off for us to invest engineer-months in a minifier that is 3% better than what's sitting on NPM today in exchange for not having a smarter type system or not having better editor support or not having the compiler be 15% faster.

If someone put up a fork with a prototype minification algorithm that produced substantial minification gains over the competition, we'd find that very convincing. If no one is bothering, that really is a sign that while everyone might enjoy the pleasant convenience of built-in minification, it's not a area where we can deliver a lot of value.

RyanCavanaugh avatar Jan 01 '16 18:01 RyanCavanaugh

If someone has waited three years without looking for an alternative, they apparently don't need minification all that badly

In our own case, this was initially not a big concern, because the code-base was smaller. But as we deal with more feature requests, each accompanied by growth in code, this is becoming critical.

If no one is bothering

My point is that so long as this feature is open, the expectation is that TypeScirpt will do something about it.

we're looking for someone to present a compelling case that TypeScript itself can do a substantially better job than off-the-shelf minifiers,

I agree that something more than simply minification of private methods would be required for TS to implement minification entirely by themselves. But providing output that Uglify can understand might be a start. I might have a go at providing more justification, but can't promise anything at the moment due to work commitments.

Our current belief is that this might be possible, but is almost certainly a huge amount of work that we could spend in more productive ways

Not sure how "a reference implementation based on some very straightforward usage of the language service" suddenly turned into a "huge amout of work" :smiley:

NoelAbrahams avatar Jan 01 '16 18:01 NoelAbrahams

With a transform based compiler (#5595) this would probably be a lot easier to implement in the compiler or using an external project.

ivogabe avatar Jan 01 '16 19:01 ivogabe

[apologies for the wall of text]

I think Ryan's suggestion that the state "NeedsProposal" means "it's not yet been made clear how to do this in a way that's a clear win over alternatives" is perfectly reasonable. There does need to be some way to express that concept.

I can speak a little to whether the current state of affairs is "good enough". Our current deployment process produces two output scripts, one of which is fairly small (~45k uncompressed) but highly size-sensitive because it's loaded in customers' pages, the other being larger (~500k uncompressed) and growing rapidly as we add features. These are produced via tsc --out [...] and closure --compilation_level=SIMPLE_OPTIMIZATIONS. I've tested various options through uglifyjs and gotten similar output, so I think we can safely assume this is close to the best we can do without type-aware optimization. This is "good enough" for the time being, but it's going to become a problem eventually. The issues we're likely to run into are download time over slow networks; but more importantly, parse time on mobile devices. The latter can be significant because parsing blocks the UI thread, and happens every time the script's evaluated (i.e., the parsed output is in-memory only, and thus not cached).

Eyeballing the final output and comparing it to the GWT output I pasted above (or any code run through either GWT or closure with "advanced" optimizations), I'd be willing to bet that we could cut these files by about 40% pre-gzipping. That's a bit of a wild-assed guess, but with the enormous number of unmangled identifiers in the output, along with the lack of inlining and other relatively simple optimizations (c.f. https://www.fullstory.com/s/fs.js), I doubt it's far off. And that kind of improvement would give us a lot more headroom for future development.

So, what's required to get this level of optimization? Reliable type information. If you look at the approach that tools like uglifyjs uses, e.g. to mangle property names, you'll see that it's kind of a hack (which is the best you can do without type information) -- you have to give it a list or pattern of identifiers that are "safe" to rename, and if you miss anything the output will be broken in unpredictable ways. OTOH, if you look at either the GWT or Closure (in "advanced" mode) compilers, you'll see that they carefully track the types of all expressions. This allows them to know not just which identifiers are private and can be renamed, but also which are external to the program (e.g., if I write window.ExposedThing = internalFunction, I need to know both that I can mangle internalFunction, and not ExposedThing).

I've considered digging into tsc to see whether it's feasible to do something similar, but have put it off both because of time constraints, and because I'm not certain whether it's compatible with the team's goals. My biggest concern is that there seems to be more of a focus on single-file compilation and working with the various --module options, than there is on monolithic compilation using ///<reference> directives. But producing globally-optimized output conflicts to a certain degree with single-file compilation. If anyone on the team could offer some insight into whether continuing to improve monolithic compilation is an explicit goal, that would help me decide whether to devote time to the problem (and recruit others I know using Typescript to contribute to optimizations).

joelgwebber avatar Jan 02 '16 17:01 joelgwebber

It's probably worth roughly sketching out what I think could work in the context of Typescript:

Because the language allows untyped expressions, and that they're fairly common, it's likely unrealistic to take quite the same approach as when compiling a much stricter source language like Java. Because the GWT compiler can rely on knowing the precise (and generally singular or very small) set of types for each expression, it can be extremely aggressive in renaming identifiers and allocating those names. Referring to the output fragment I pasted above, you'll see lots of things like:

function abc(a,b) { if (a.a == b.a) {b.b(a, b); }
// ...

Outside of external references, you'll see essentially no human-readable identifiers, and the names are mostly linearly allocated in small scopes (so you get lots of a, b, ..., aa, ab, etc). If you're careful about sorting the output, you can even get significant improvements in gzip performance by reducing entropy within the compression window.

With less-reliable type information, I suspect it would be much easier to rely on a single scope for allocating mangled identifiers (with the possible exception of function parameters, which most optimizers already rename locally). So in essence you'd end up with a single "rename dictionary" which would contain all the identifiers that can be safely renamed, such that all instances of someIdentifier get renamed to abc, regardless of their scope. This is sub-optimal, but works fairly well in practice (I believe most products that use Closure do so with the set of flags that causes it to work this way, or at least did as of a few years ago).

An identifier would be considered "rename safe" if the scopes of all references to it can be determined to originate within Typescript source. Any reference via an expression of unknown type (e.g., bar in var foo = untypedFunc(); foo.bar()) or an explicitly external type (e.g., via some_lib.d.ts) would be excluded from renaming. This works to the extent the code contains explicit or inferred type information, and removes the need for an explicit "externs" file, which is very error-prone.

It would be nice to get function/method inlining working as well, but it has stricter requirements. To get much benefit from it, you need to be able to precisely identify all references to the function. Otherwise you can't remove it. This may sound like a small win, but in code with lots of trivial accessor methods, it can really add up.

joelgwebber avatar Jan 02 '16 17:01 joelgwebber