New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: minification #8

Open
RyanCavanaugh opened this Issue Jul 15, 2014 · 135 comments

Comments

Projects
None yet
@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Jul 15, 2014

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?)
@chaser92

This comment has been minimized.

Copy link

chaser92 commented Aug 7, 2014

I think that this isn't the best idea - TypeScript should better do what it's best at, one tool should serve one purpose. There are a lot of great minifiers out there.

@NoelAbrahams

This comment has been minimized.

Copy link

NoelAbrahams commented Aug 7, 2014

@chaser92, this request is to minify TypeScript code, not JavaScript code. A minifier that uses the information (primarily information on access modifiers) available to the TypeScript compiler will be much more efficient than any JavaScript minifier out there.

I am personally very eager to see this implemented.

@RyanCavanaugh

This comment has been minimized.

Copy link
Member

RyanCavanaugh commented Aug 7, 2014

Motivating examples of things that TypeScript could minify but an external minifier could not would be useful. Things like closure and uglify do a really good job already; we'd have to have evidence we could make real improvements over them to justify spending time on it.

@NoelAbrahams

This comment has been minimized.

Copy link

NoelAbrahams commented Aug 11, 2014

The following TypeScript code

class Greeter {

    private greeting: string;

    constructor (message: string) {
        this.greeting = message;
    }

    public greet() {
        console.log(this.getMessage());
    }

    private getMessage() {
        return "Hello, " + this.greeting;
    }
}

Can be compiled into JavaScript that when run through an external minifier results in the following:

var Greeter = (

    function () {

        function a(b) {
            this.greeting = b
        }

        a.prototype.greet = function () {
            console.log(this.getMessage())
        };

        a.prototype.getMessage = function () {
            return "Hello, " + this.greeting
        };

        return a
    }
)();

Problems:

  • The private field greeting has not been minified.
  • The private method 'getMessage` has not been minified.
  • The type name "Greeter" has been mangled into "a". This breaks code such as (/function (.{1,})\(/).exec((instance).constructor.toString()) for obtaining the type name at runtime.
  • The constructor parameter "message" has been mangled into "b". This breaks code that attempt to perform dependency injection by parsing constructor arguments.

In summary, even in just this simple snippet of code TypeScript can improve on an external minifier, both by mangling names that should have been minified as well as optionally leaving names untouched.

@RyanCavanaugh

This comment has been minimized.

Copy link
Member

RyanCavanaugh commented Aug 11, 2014

If I use the Closure Compiler, it goes from code like this:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        console.log(this.getMessage());
    };

    Greeter.prototype.getMessage = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();


var x = new Greeter();
x.greet();
console.log(x.getMessage());

to this:

var b = new (function() {
  function a(a) {
    this.c = a;
  }
  a.prototype.b = function() {
    console.log(this.a());
  };
  a.prototype.a = function() {
    return "Hello, " + this.c;
  };
  return a;
}());
b.b();
console.log(b.a());

Here, the greeting field and getMessage names have been correctly minified. The "over-minification" of other variables leads to my next discussion point on this.

Some people think class names, property names, parameter names, local names, etc are meaningful runtime metadata, other people think they're not. Some other people think only some of their property names, parameter names, local names, and so on are things that should be minified. Among those people, there's disagreement over how those names should be specified (globally? locally? in the code? in a config file? on a commandline?). Nearly everyone believes that their set of rules is the only one that makes sense.

The only path forward that could beat existing minifiers also involves a ton of configuration for what the allowed set of minifications even is; implementing and testing all these rules would be very expensive. It's a lot of investment for what is probably a few percent improvement (especially after gzipping) over the state of the art here. That's why we want to see compelling examples for where only the TypeScript compiler could minify and do a meaningfully better job than any existing tool.

@NoelAbrahams

This comment has been minimized.

Copy link

NoelAbrahams commented Aug 12, 2014

@RyanCavanaugh,

Regarding the under-minification problem, it looks like the code in your post was minified using the "advanced" option of the closure "compiler". And yes, that appears to solve the problem in this simple case. However, consider this slightly more involved example:

class Greeter {

    public greet() {
        console.log('greet');
    }
}

function createInstance<TType>(name:string): TType {

    return new window[name]();
}

var x = createInstance<Greeter>('Greeter');
x.greet();

Basically, we have introduced a class factory function. The closure compiler, with the advanced option, minifies this to

(function() {
  function a() {
  }
  a.prototype.a = function() {
    console.log("greet");
  };
  return a;
})();
(new window.Greeter).a();

Clearly this is going to fail at runtime. The solution is to export the "Greeter" symbol:

window["Greeter"] = Greeter;

Seems simple enough. But in large projects with hundreds of classes, this is not trivial. TypeScript understands this code better, because it knows that function Greeter is a class name.

More importantly, the problem I have with the closure compiler is that it requires the entire code-base to be minified in one go. This is not feasible in large projects, where there is separation between library code and client code. In this situation it is necessary to declare externs, which ultimately results in maintaining one's public API in duplicate.

With regard to the second issue that was raised, namely the problem of configuration, that, I guess, is an implementation detail: if there is demand for configuration then that would have to be dealt with. But it seems strange to decline an entire issue on that basis.

A possible halfway solution would be for TypeScript to provide an option to generate closure-style extern files or to export symbols (class names).

@danquirk

This comment has been minimized.

Copy link
Member

danquirk commented Aug 12, 2014

The configuration is not just an implementation detail. The fact that we can go back and forth all day with different code examples that need differing amounts of minification is proof of the need for either a) very simple minification algorithms b) extremely customizable minification options. You've already identified multiple issues that absolutely demand customization to work at all.

In addition, we're still talking about this nebulous concept of 'the TypeScript compiler understands the code better so it should just do this example correctly' (for some definition of correctly). There's still very little here that is actually stating proposed solutions to classes of problems which you could put a configuration over the top of.

@NoelAbrahams

This comment has been minimized.

Copy link

NoelAbrahams commented Aug 17, 2014

To summarise the discussion so far:

  • The JavaScript generated by TypeScript is not optimal in terms of providing that output as input to a simple minifier. This is largely due to private methods going on the prototype. A developer wanting to write code that is optimal for a minifier would have written those private methods as simple functions within the class closure.
  • This problem can be solved by running the output through an advanced minifier (for example the closure compiler with the "advanced" option).
  • Unfortunately the closure compiler requires all symbols to be within sight of the minification run. If they are not then those symbols must either be exported (added using bracket notation) or an externs file must be created, declaring the symbols that should be preserved.
  • User preferences for minification can be diverse.
  • The TypeScript compiler has a superior information set with which to perform minification than a JavaScript minifier; this information set includes having access to the following modifiers "class", "private", "public", "constructor" and the API of external libraries through their declarations files.
  • The biggest advantage that a TypeScript compiler has over ordinary minifiers is being able to safely perform minification on any subset of the code-base. By "safely" I mean that, firstly, exported classes and their public API can be preserved, and, secondly, calls made from within a class into external libraries can also be preserved with recourse to the information in their respective declarations files.

In the light of the above, I have three basic proposals listed in order of preference:

A. A fully functional minifier provided by TypeScript.
We provide two compiler options

  • --minify-simple - Preserves class names, constructor signature...
  • --minify-advanced - Performs a more aggressive minification.

In both cases, private fields and methods would always be minified.

B. TypeScript generates externs files for providing to the Closure Compiler if specified.

C. TypeScript only minifies private fields and methods if specified.

It is conceivable that with option A there will be many people who would like a halfway solution between "simple" and "advanced" minification, e.g. preserve class names but minify constructor signature. In this instance, it may be possible for those concerned to run the output generated by TypeScript through a third-party minifier that provides more specific options.

@ghost

This comment has been minimized.

Copy link

ghost commented Aug 19, 2014

I like your B suggestion (TypeScript generates externs files for providing to the Closure Compiler). Not sure how it works but I like the sound of it when considering the points that everyone else is making.

@bryanerayner

This comment has been minimized.

Copy link

bryanerayner commented Aug 23, 2014

TL;DR
Perhaps Data-Annotations could be added to Typescript's syntax to provide developers with an easy way to tell the compiler what should, and should not be overly minified.

I have been writing a large Angular app using Typescript. I've been painfully watching the size of the JS grow and grow, and would personally LOVE to have some advanced compilation support that only Typescript can provide. IMO Typescript can do an incredibly good job at minifying code, better than closure because you're not limited to comments for specifying compiler directives.

For an Angular app, there needs to be a high level of granularity of what functions and properties are minified (a la Closure Compiler's advanced mode) and what properties should be left as-is. They are referenced in the HTML and oftentimes used by Angular to correctly link the DOM to JS. You'd need a solution on an item by item basis in order to accomplish this in a way that would make it easy to use.

For example, much in an Anuglar directive can be truly 'Javascript Only', and I would like advanced minification on it. However, there are some variables that need to be exposed to HTML, outside of the javascript engine.

If we were able to use something similar to a C# data-annotation on class properties, that would be a much better method than Closure compiler's recommendations. I've seen a lot of Javascript written for the Closure compiler that uses array notation to reference unminified properties - This is a pain to write. Any time you reference a property by a string in Javascript, it just feels muddy to me.

I've been using Newtonsoft.Json on a dot Net backend. We directly serialize our business logic models to the client side - Of course, we want to keep some things hidden from JSON serialization. For those without a C# background, a data annotation looks like this:

Imports Newtonsoft.Json

class Klass
{
    [JsonIgnore]
    public string[] SomethingVeryLarge;

    public string SomethingMoreManageable;
}

The [JsonIgnore] data annotation instructs Json.Net to overlook this property when parsing an instance of Klass.

Having something like data-annotations could provide the compiler with a really good system of flags, that could be used for this advanced minification support, or other compiler features. I could see this syntax eventually being usable Typescript programs to further extend the language.

@NoelAbrahams

This comment has been minimized.

Copy link

NoelAbrahams commented Aug 24, 2014

@bryanerayner,

there are some variables that need to be exposed to HTML, outside of the javascript engine.

Yes, that's a relevant point as well. This is also the case when using KnockoutJS, for example:

class ViewModel {

  [minifyIgnore]
  public foo = ko.observable('bar');
}

because foo is referenced in the HTML:

<div data-bind="text:foo" />
@eggers

This comment has been minimized.

Copy link

eggers commented Sep 11, 2014

I would love a typescript aware minifier. Also, because I've had some issues with ng-min not working very well on tsc generated javascript. (I haven't tried ng-annotate yet)

@WanderWang

This comment has been minimized.

Copy link

WanderWang commented Sep 16, 2014

I Agree with @RyanCavanaugh
I'm working for a Open Source HTML5 Game Framework called EGRET
Many of our developers thinks that our game.min.js should be smaller and smaller .
Now we compress our game.min.js with Google Closure Compiler SIMPLE_OPTIMIZATION , there are some reason we abandon ADVANCED_OPTIMIZATION

  • It's very hard to use ADVANCED in a complex project with Zero bug . We had to test the whole the test case carefully again . When we turned to SIMPLE mode , it has too many private long-named field not be optimized , C is a useful solution with SIMPLE mode
  • We should support our customer a lib.min.js and there are many public api inside . But ADVANCED_OPTIMIZATION delete almost all the apis because it thinks that the apis not be used . To solve this problem , we should provide a extern-file to Closure Compiler , but we have to many API . B solution with ADVANCED mode is a good idea , because of tsc can generate the extern files very easy ( such as .d.ts )

So, I hope both B and C could be added to tsc .
By the way ,forgot A ,please ^_^

@mirhagk

This comment has been minimized.

Copy link

mirhagk commented Sep 29, 2014

I'm noticing that the problem with using Closure is that there is information about visibility that TypeScript is aware of that Closure can't know.

This is why the private members stick around when using simple with Closure. Using advanced can cause headaches.

TypeScript can make it easier to use advanced with option B. It could also potentially make simple optimizations with closure better if it could communicate to closure which methods/variables are private. It could emit JSDoc comments to decorate fields with @private.

Currently the Google Closure compiler doesn't use these hints for anything useful, but providing that information for it doesn't hurt (since it removes comments) and it gives minifiers more information to optimize with.

@antoinerousseau

This comment has been minimized.

Copy link

antoinerousseau commented Jan 22, 2015

If option A is fully efficient, I don't see why you would need B or C!

I would love to have option A's --minify-advanced!

@mirhagk

This comment has been minimized.

Copy link

mirhagk commented Jan 22, 2015

I think the issue is that the compiler shouldn't necessarily be responsible for minification. I would much rather see all the information that TypeScript knows be emitted as jsdoc comments. That way JavaScript tools can utilize that information without needing to have a TypeScript parser.

@ghost

This comment has been minimized.

Copy link

ghost commented Jan 22, 2015

Don't compilers generally have a switch to optimize for file size? Why not this one?

@mirhagk

This comment has been minimized.

Copy link

mirhagk commented Jan 22, 2015

Compilers don't usually have a goal of near 1:1 mapping with source.

The point is that generating the resulting code is completely different with optimizing for file size (and other optimizations) than what it currently produces. I'd suggest a separate tool is created for an optimizing compiler (one that optimizes for either file size or performance), that makes use of the API tsc offers. I was planning on experimenting with the tsc compiler API so I may do an experiment in producing minified output.

@ghost

This comment has been minimized.

Copy link

ghost commented Jan 22, 2015

The goal of the TypeScript compiler could be near 1:1 mapping of source unless the /min switch is set, in which case the goal would be to minimize it to the hilt without changing its exports.

@mirhagk

This comment has been minimized.

Copy link

mirhagk commented Jan 22, 2015

Yes that's true, but then the back-ends are basically completely separate. I'd recommend implementing it as a separate module/project that uses the API, then if it does prove very useful it can be evaluated to be merged as part of the tsc command line.

@joelgwebber

This comment has been minimized.

Copy link

joelgwebber commented Mar 13, 2015

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.

@NoelAbrahams

This comment has been minimized.

Copy link

NoelAbrahams commented Mar 13, 2015

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.

@joelgwebber

This comment has been minimized.

Copy link

joelgwebber commented Mar 13, 2015

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.

@aluanhaddad

This comment has been minimized.

Copy link
Contributor

aluanhaddad commented Dec 30, 2016

@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';
}
@sagifogel

This comment has been minimized.

Copy link

sagifogel commented Dec 30, 2016

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.

@aluanhaddad

This comment has been minimized.

Copy link
Contributor

aluanhaddad commented Dec 31, 2016

@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.

@evmar

This comment has been minimized.

Copy link
Contributor

evmar commented Dec 31, 2016

@aluanhaddad

This comment has been minimized.

Copy link
Contributor

aluanhaddad commented Dec 31, 2016

@evmar My understanding is that Closure's type system is nominal and that @implements is required, I may be wrong (or out of date), but if so that is not even a subset of TS, it is a complete divergence on both the technical and conceptual level and fundamentally incompatible.

@evmar

This comment has been minimized.

Copy link
Contributor

evmar commented Dec 31, 2016

@aluanhaddad

This comment has been minimized.

Copy link
Contributor

aluanhaddad commented Jan 1, 2017

Fair enough, but that simply is not TypeScript. It is Closure.

I am not going to start writing Closure.
I know you are not asking me to do that in any way, but bear with me.

I think people should be aware of what they are getting into.

Treating TypeScript as a syntactic veneer over a language other than JavaScript sounds very dubious.

Closure is a subset of JavaScript which, from what I can tell, is based on Java.
Frankly, trying to use a language that didn't even have a way to pass one method to another until 2014 as a basis for statically analyzing JavaScript seems a little off in left field.

@sagifogel

This comment has been minimized.

Copy link

sagifogel commented Jan 1, 2017

Closure compiler is a compiler for JavaScript.
You write your JavaScript with annotations in order to gain static code analysis for a dynamic language.
The main difference is the modeling.
Closure Compiler knows interfaces, classes, polymorphism and all OO paradigms.
These concepts are expressed within the structure of your code, therefore you can (don't have to) define
interface implementations.
If you write your code in Java, C#, (same name for class and interface) or try to compile it in closure compiler you will get an error.
In my opinion, defining the same name for a class and an interface is wrong even if the language allows it.
It may create confusion and may shadow the main functionality of the class.
In addition, I don't understand why not to define the property as part of the class.
It is so strange that even the TypeScript compiler does not warn you in case you don't implement the contract of the interface Greeter, so why bother to write an interface?

@aluanhaddad

This comment has been minimized.

Copy link
Contributor

aluanhaddad commented Jan 1, 2017

Here is a use case

interface Product {
  readonly name: string;
  readonly price: number;
  readonly inStock: boolean;
}

class PowerSaw implements Product { // Error
  constructor(properties: Product, readonly blades: Blade[]) {
    Object.freeze(
      Object.assign(this, properties)
    );
  }
}

function addToOrder(product: Product) { ... }

addToOrder(new PowerSaw(...)); // Error

By adding

interface PowerSaw extends Product { }

both errors are fixed.

@mprobst

This comment has been minimized.

Copy link
Contributor

mprobst commented Jan 2, 2017

@aluanhaddad indeed, if you are piping TypeScript through Closure compiler, you are restraining yourself to write in the common language subset of TypeScript and Closure compiler, or more specifically, the language subset your TS->Closure translator enables you to use.

Whether that's practically useful depends on the size of that subset, and a slew of less fundamental and more pragmatic issues (error behaviour, debuggability, optimization quality, etc). An interesting question is also the inverse, that is whether it's pragmatic not to use Closure compiler.

I have first hand experience with several applications where using Closure Compiler as an optimization step after TypeScript is pragmatically useful, and not using would be prohibitive (due to code size). Whether the same is true for you of course depends on your use case and many other factors.

FWIW, the nominal vs structural issue is not actually a problem, Closure compiler supports structural interfaces using @record, and the types vs values namespace issue can of course be fixed by escaping interface names.

@MGunlogson

This comment has been minimized.

Copy link

MGunlogson commented Jan 3, 2017

I'm partial to having a preset in typescript to emit Closure compatible JS. Basically save types as Jsdoc, check for a couple things that prevent advanced optimizations, and run the right emit settings.

IMO, a tool in the middle shouldn't be necessary. Typescript already has special support for react and different flavors of JS, adding explicit support for Closure would be a great selling point for typescript.

It really just depends on how important it is to the Typescript team. I have a feeling the need for dead code elimination is only going to increase as js gets more widely used, plain minification isn't going to be enough forever. Closure is hands down the best tool for this and the type system is largely compatible already.

@aluanhaddad

This comment has been minimized.

Copy link
Contributor

aluanhaddad commented Jan 3, 2017

@evmar I looked over the tsickle repo and the open issues to see what it currently offers as I may well have to use it at some point in the future.

It seems like there are some rough edges but the commitment that you have shown to abstracting away the differences is really impressive. It seems you have made it a fundamental design priority that the inherent mismatches between the two typesystems be handled internally within tsickle. This is not trivial. Clearly you value developer experience and, especially as some frameworks don't place enough value on it, I really appreciate it. Thank you ❤️

@evmar

This comment has been minimized.

Copy link
Contributor

evmar commented Jan 3, 2017

@MGunlogson I think long term the best place for us would be as some sort of plug-in emitter rewrite pass (using the same mechanism TS uses to downlevel async/await, or downlevel ES6->ES5). But I say plug-in because don't think the TS team wants to own it, as there's a lot of finicky details in making Closure work that unfortunately will require a lot of time. Depending on how you look at it the type systems are either "mostly compatible" or "fundamentally incompatible".

@aluanhaddad thanks! I would add that I don't think Closure minification is necessarily the best solution for TS, but rather that it's a pretty good local maximum. And we're particularly committed to it because we're making TS interop with a large body of existing Closure code.

@mblandfo

This comment has been minimized.

Copy link

mblandfo commented May 22, 2017

@RyanCavanaugh

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.

Proposal: Typescript has a tsconfig option "minifyPrivateMembers"

One compelling case is any front end data binding framework such as Angular, Knockout, React, etc. Through data binding we have references to javascript variables in html code. It'd be really nice to be able to mark things as "private" and have those be minified.

Using google closure compiler would require using an externs file for all the public properties I want to keep. That would be awful to hand maintain. Perhaps something could generate an externs file out of everything that's not marked private and then run closure compiler, but it'd be much nicer if typescript could just minify anything marked private. Typescript wouldn't even have to minify anything else, uglify can do the rest.

I have a library using typescript with knockout, and it's 418,828 bytes with uglify and 302,158 bytes with closure compiler. That's about 28% smaller. I'd very roughly estimate real savings would only be half that, since that closure compiler result also obfuscated public things.

@bryanrideshark

This comment has been minimized.

Copy link

bryanrideshark commented May 23, 2017

@mblandfo , can you submit a more formal proposal as a separate issue? I think that has a better chance of being noticed by the core team, and would provide a better place to discuss the specifics of what you're after.

I think just having that one setting would be enough - especially since we now have a plugin compatible compiler, the time has come for this to see the light of day.

@mrkite

This comment has been minimized.

Copy link

mrkite commented Aug 31, 2017

I think tsc should definitely support this, since it can do related optimization better than 3rd party tools. For example, using enums result in a bunch of useless code, adding string mappings and whatnot.

However, a minifier option would imply no undeclared external references. tsc would then be able to make optimizations like replacing all enum usage with numeric literals.

@HolgerJeromin

This comment has been minimized.

Copy link
Contributor

HolgerJeromin commented Sep 1, 2017

@mrkite Did you know that const enums exists?

@JohnWeisz

This comment has been minimized.

Copy link

JohnWeisz commented Jan 14, 2018

Decorators

Currently, it is impossible to use decorators with variable-renaming minification, as neither UglifyJS nor closure-compiler would rewrite property/method names in __decorate calls correctly.

@j-oliveras j-oliveras referenced this issue Jun 20, 2018

Closed

Optional name mangling of private members #25089

4 of 4 tasks complete
@pjebs

This comment has been minimized.

Copy link

pjebs commented Jan 6, 2019

This issue should be closed. It would be amazing to have a typescript-aware minifier but when an issue is 5 years old nothing is going to happen. Leaving it open just fills my heart with unnecessary hope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment