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

hi i.ve read this long thread while I need to minimize my code too. I think we need to take the application development under the productivity point of view. We can of course use many tools to achieve all the aspects of development, ie prototyping, developping, documenting, productizing, deploying. At the end, we need to be expert in several evolving technologies and we loose time on concerns which are not the main purpose of developpers whch is : focus on the application features. It is why I always promote the integration inside the typescript tooling ecosystem of more features than just grammar and transpiling ones. Tight integration with IDE, debugging', minification, optimisation, uglification, testing coverage, and many more are also very important to increase the development productivity. I.m a former smalltalk 80 as well as gwt early adopter developper, and i always appreciated the all in one box that those technics proposed then. I eager to see in the future the same approach in typescript for a language I'm more and more fond of nevertheless. regards xavier

xmehaut avatar Jan 27 '16 01:01 xmehaut

@mmacfadden Since you mentioned interest, I thought I'd give you a quick update on where I am. I'm working on shortening identifiers which can be considered "internal". I am currently testing the exclusion of identifiers that implement external interfaces. Shortening of identifiers which can be considered internal is a big gain. Update: Typescript minification with TsProject is complete.

ToddThomson avatar Jan 27 '16 18:01 ToddThomson

I apologize for making a very long thread longer. Where did this end up? It seems like a lot of people (including me) would love to see a path for minified output, done in a way that takes advantage type information to optimize smaller/better. Lots of us have no preference of whether it happens natively inside TypeScript, via type information passed to uglify, type information passed to Closure, or other means. Do any of these paths already work? Or are all still in various stages of progress?

kylecordes avatar Mar 18 '16 00:03 kylecordes

Kyle: we have Closure minifying code that was processed by sickle successfully, with property renaming and dead code removal enabled, but without type based aliasing. We don't have an easy to reproduce build setup at the moment though :-(

@martine knows more.

Kyle Cordes [email protected] schrieb am Do., 17. März 2016 um 17:26 Uhr:

I apologize for making a very long thread longer. Where did this end up? It seems like a lot of people (including me) would love to see a path for minified output, done in a way that takes advantage type information to optimize smaller/better. Lots of us have no preference of whether it happens natively inside TypeScript, via type information passed to uglify, type information passed to Closure, or other means. Do any of these paths already work? Or are all still in various stages of progress?

— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/8#issuecomment-198143200

mprobst avatar Mar 18 '16 00:03 mprobst

https://github.com/angular/sickle is undergoing active development because we're using it within Google. Currently Closure's optimizer is hard to use but it's the best optimizer we know of.

Our basic goals/roadmap are:

  1. make every TypeScript program at least accepted by the Closure compiler
  2. support Closure renaming optimizations
  3. support Closure type-based renaming optimizations
  4. make all of this work with no worries

We're somewhere around step 2: current sickle+Closure output successfully applies renaming and minification, which includes inlining, constant propagation, dead code elimination, and all those nice things.

To be clear, you can do a lot of property renaming without any types. Even if you have two unrelated objects A and B with a internalProperty field, it's safe to rename internalProperty to a everywhere. Uglify can do that already, I believe. Types only matter in that when you have a lots of objects -- to be able to rename both A.internalProperty and B.unrelatedInternalProperty to the same a. Closure supports this and we're working on making the TypeScript types propagate to help. (Structural typing will likely make this hard...)

Regarding step 4, we'd like to make it so that you can write native-feeling TypeScript code and have all the optimization info trickle into Closure without needing to worry about what Closure will do to your code. To that end we've done some work on making it so when you use declare var foo; we specially mark the variable foo to prevent renaming. (There's lots of other work, like restricting TypeScript features that prevent optimization: https://github.com/angular/sickle/issues/23 .)

Our only current client is the internal Google TypeScript build, which internally wraps tsc, so there's not much of a command-line interface to sickle yet. But it shouldn't be more than a few lines of code for someone to hook it in to their existing build. If you'd like to look into this I filed https://github.com/angular/sickle/issues/104 to gather requirements.

evmar avatar Mar 18 '16 01:03 evmar

First of all I think like something like this is really important to generate high quality code and high quality output is something that I would hope for in a stricter tool chain. I understand that the typescript compiler itself isn't necessarily the best place to put it. Maybe a plugin or something would be good because it can still access the rich semantic information of the typescript compiler.

One thing about single-module optimization that many people appear to be overlooking is that renaming private identifiers isn't trivial as assigning a, b, c. This is because subclasses share the same namespace and you don't necessarily know all your subclasses. A simple approach is to use Root.aa, Root.ab, Root.ac in the top level class and Sub.ba, Sub.bb, Sub.bc in the first level class and so on (this would work up to about 60 classes deep). But you still have to worry about subclasses using those names. (maybe Root._tsa_a, Root._tsa_b and Sub._tsb_a, Sub.tsb_b to be pedantic?)

The big question here is also the size of the compilation unit. If we assume whole-program like closure advanced optimizations then you can just rename everything like closure does, however if it is module wide there is very little renaming space that can be used (locals and privates (not protected) are all I can think of right now) because you need to keep "binary compatibility".

Moving past just identifier entropy more "logic" based optimizations can be applied.

  • Constant prorogation can be applied (this will become possible with other ES6 compressors though).
  • More inlining because the exact type can be known.

Furthermore if this path is taken annotations that can be added to really allow for smarter compilation. For example pure or const attributes to allow more aggressive (but safe) optimizations.

That being said I see the most gains from intelligent renaming of privates. This is one of the largest things that can't be done by closure and it would be fairly simple to implement. Then you could use a secondary compiler to perform further optimization for the time being.

kevincox avatar Jun 22 '16 04:06 kevincox

I also want to see the Closure compiler integration implemented. Currently we have an internal framework for making HTML5 games and we use Closure Compiler for type checks and minification. Unfortunately we use only SIMPLE optimizations, because when we tried to use the ADVANCED optimizations we found many bugs due to insufficient type annotations on our code.

Typescript compiling to annotated JS code that supports ADVANCED optimizations out of the box would be definitively a killer feature for developers that are still not sure about investing scarce resources to port their code bases to TypeScript.

ex avatar Sep 06 '16 18:09 ex

check out https://github.com/angular/ts-minify

graingert avatar Sep 14 '16 11:09 graingert

Also http://blog.mgechev.com/2016/07/21/even-smaller-angular2-applications-closure-tree-shaking/ have interesting results.

It seems that the type information allows to reduce the size from 150 to 20 kb for hello world angular 2 application.

snrostov avatar Sep 14 '16 11:09 snrostov

+1

If Typescript can't do this then i think it sholud provide plugin ecosystem, so other people can jump into it and all information that ts have, then no just minifier other things will also be developed like pre-processors etc.

dev-mraj avatar Nov 10 '16 20:11 dev-mraj

For those who might be interested, I've decoupled the Typescript minifier feature from TsProject so that it is now a standalone node package TsMinifier .

As mentioned above, TsMinifier utilizes the Typescript AST to more effectively mangle identifier symbols. It supports jsDoc annotations ( currently only /** @nomangle */ ) and can optimize mangling through the use of an external namespace convention.

ToddThomson avatar Nov 23 '16 16:11 ToddThomson

I need help in adding the minifier to my TypeScript compiler options. how to add it to the tsconfig.json ? how to use the --minify-advanced with source maps ?

nisimjoseph avatar Dec 06 '16 06:12 nisimjoseph

@nisimjoseph the TypeScript compiler does not have minification settings. If third party tools are putting additional configuration inside of the compilerOptions property, breakage and incompatibility become likely.

aluanhaddad avatar Dec 06 '16 07:12 aluanhaddad

thank you @aluanhaddad , I am using Webpack and want to use that Minify Advanced to make the code scrambled. do you have any guidance for that?

nisimjoseph avatar Dec 06 '16 07:12 nisimjoseph

I'm afraid I'm not the person to ask. I have used Webpack's uglify minification support and it works well for me. Closure and tsickle are not roads I want to go down.

aluanhaddad avatar Dec 06 '16 08:12 aluanhaddad

I am the author of typescript-closure-compiler. Basically it is a tool that emits files that are compatible with google closure compile. I've also created a playground that can show you the generated output. My TSFunq project uses this tool for minification.

sagifogel avatar Dec 29 '16 23:12 sagifogel

@sagifogel Not to downplay the utility of your tool, but it fails in common idiomatic TypeScript use, resulting in broken JavaScript. Here is an example


class Greeter {
    greeting: string;
    constructor(message?: string) {
        this.greeting = message || this.defaultGreeting;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}
interface Greeter {
    defaultGreeting: string;
}
function createGreeter() {
    const greeter = new Greeter('World');
    greeter.defaultGreeting = 'All';
}

produces

"use strict";

/**
 * @constructor
 * @param {string=} message
 */
function Greeter(message) {
    "use strict";
    /**
     * @type {string}
     */
    this.greeting;
    this.greeting = message || this.defaultGreeting;
}

/**
 * @return {string}
 */
Greeter.prototype.greet = function () {
    return "Hello, " + this.greeting;
};

/**
 * @interface
 */
function Greeter() {
}

/**
 * @type {string}
 */
Greeter.prototype.defaultGreeting;

function createGreeter() {
    /** @const {Greeter} */ var greeter = new Greeter('World');
    greeter.defaultGreeting = 'All';
}

aluanhaddad avatar Dec 30 '16 05:12 aluanhaddad

For me your definition of "common idiomatic TypeScript" is wrong approach. I don't think that you should code like that just because you can. Anyway I'll fix it in the next release. Thanks.

sagifogel avatar Dec 30 '16 21:12 sagifogel

@sagifogel Sorry, I wasn't trying to be a contrarian.

I agree that my example isn't great code but declaration merging is a very common practice, and it is fairly essential to the language.

More broadly, my point is that trying to reify interfaces is a huge mistake. It causes name collisions immediately which will not only be surprising for TypeScript programmers, because we expect interfaces to never conflict with names in the value space, but also because interfaces are strictly structural in this language. Any system which creates (or relies on) nominal interfaces in JavaScript is a massive change and (IMO) is a terrible direction.

aluanhaddad avatar Dec 31 '16 05:12 aluanhaddad

In the limit, you can always write code that will defeat optimization (e.g. just use eval). So ultimately you have to choose a subset of JS (and perhaps even a subset of TS) that you can optimize.

Ideally you could warn the user when they fall out of that subset, though the "undefined behavior" surprises from C compilers indicate that it's hard to do perfectly.

Pragmatically we've found that for our users (who likely lean more towards coming from non-JS languages, and are unlikely to do cutesy JS tricks) a fairly straightforward translation works out well enough with the Closure compiler.

Here are some open bugs we have on making our tooling warn when you write TS that the Closure compiler eats: https://github.com/angular/tsickle/labels/prevent%20closure%20antipatterns

On Fri, Dec 30, 2016 at 9:13 PM, Aluan Haddad [email protected] wrote:

@sagifogel https://github.com/sagifogel Sorry, I wasn't trying to be a contrarian.

I agree that my example isn't great code but declaration merging is a very common practice, and it is fairly essential to the language.

More broadly, my point is that trying to reify interfaces is a huge mistake. It causes name collisions immediately which will not only be surprising for TypeScript programmers, because we expect interfaces to never conflict with names in the value space, but also because interfaces are strictly structural in this language. Any system which creates (or relies on) nominal interfaces in JavaScript is a massive change and (IMO) is a terrible direction.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/Microsoft/TypeScript/issues/8#issuecomment-269850019, or mute the thread https://github.com/notifications/unsubscribe-auth/AAAPB6gIA67lP9UcwlayWYxh9jUNHLzMks5rNeR6gaJpZM4CNZxl .

evmar avatar Dec 31 '16 06:12 evmar