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

@mhegazy, so theoretically speaking, given the compiler is now exposed for third-party/external extensibilities, we can get a hook into AST and then implement the ultimate minification possible with all the trans-compilation context info. In this case, minification should be a feature of tsc, so consumers of TS should not rely on the external module (uglifyjs etc.).

ghost avatar Aug 10 '15 20:08 ghost

@jasonwilliams200OK i agree. i believe the request here is for tsc to subsume your minifier in the tool chain. i do not think you would want to run tsc --minify then run your minifier again.

mhegazy avatar Aug 10 '15 20:08 mhegazy

++

electricessence avatar Sep 14 '15 04:09 electricessence

I do not understand why those things in ts 1.7 roadmap can be more important than minify. I had no choice but shipped my code with full function names. I am feeling myself as unprofessional as selling apples with apple tree attached, selling house without scaffold staging removed, taking my girlfriend to motel with her mom in the trip.

hcapp01 avatar Sep 28 '15 05:09 hcapp01

I do not understand why those things in ts 1.7 roadmap can be more important than minify.

Whaaaat? "Colorization of JSX code in VS 2015" (https://github.com/Microsoft/TypeScript/issues/4835) is NOT important than minification? :stuck_out_tongue_winking_eye:

Agree minification deserves some love. Not only shortening of names and elimination of whitespace but also some deep optimizations, joining of scattered file content etc. too. But naturally this is a complicated task which can be carried out in phases; basic->advanced.

ghost avatar Sep 28 '15 05:09 ghost

Because TypeScript emits idiomatic, valid JavaScript, I suspect it isn't a priority because there are plenty of other tooling out there that does better than likely what the TypeScript can hope to achieve in the short term. Honestly folks, if you depend on TypeScript for you minification, you are likely not going to do an effective job of it. There is the Closure Compiler and UglifyJS. You can have those today, actually you could have had them before TypeScript.

kitsonk avatar Sep 28 '15 06:09 kitsonk

@kitsonk, there are some problems with using closure and uglify that have been discussed above.

NoelAbrahams avatar Sep 28 '15 18:09 NoelAbrahams

Maybe I'm missing something, but I've been having significant difficulty in getting sourcemaps and uglify/minify to work as expected. What I really want is a TSC.exe compiler option to minify the file with sourcemaps. IMO, simply stated, if you are using AMD or any other module based code, you really don't care about how the resultant JS looks because you have the sourcemaps.

Here's what I've found (spend hours and hours on this):

  1. tsc with sourcemaps works perfectly without minification/uglify.
  2. gulp-typescript + gulp-sourcemaps generates different sourcemaps than 1)
  3. Any attempt at rendering minified files externally using gulp-sourcemaps, say in a 'min' folder creates strange references that don't resolve without overriding the sourceRoot with a function.

Ultimately, the above basically says there are bugs in the gulp plugins, but I would be happy if simply my resultant JS files were minified straight out of the TypeScript compiler.

electricessence avatar Oct 02 '15 15:10 electricessence

Also, it would be neat if you could replace the __extends code with an AMD module called 'extends' or something. :) Could take a chunk out of the total code.

electricessence avatar Oct 02 '15 15:10 electricessence

@mhegazy Is there any way with 1.7 to control or get access to the text writer or emitter? I just want to do a bit of experimenting with whitespace removal and private identifier mangling.

ToddThomson avatar Dec 04 '15 23:12 ToddThomson

For anyone who is interested.. I've experimented with walking the container nodes and minimizing blockscopedvariables. This requires a minimal amount of code, so I'm going to add it to TsProject on NPM and GitHub . It will work only on bundles. As for whitespace removal, there is currently no way to change the way that indentation works in the js text writer. However, It is also a simple task to use the Typescript Scanner in a post emit step to remove all whitespace trivia and newline trivial.

ToddThomson avatar Dec 12 '15 23:12 ToddThomson

Fantastic! That's a great first step.

On Sat, Dec 12, 2015, 5:08 PM Todd Thomson [email protected] wrote:

For anyone who is interested.. I've experimented with walking the container nodes and minimizing blockscopedvariables. This requires a minimal amount of code, so I'm going to add it to TsProject. It will work only on bundles. As for whitespace elimination, there is currently no way to change the way the indentation works in the js text writer, so this will have to be done as a processing step after the bundle emit.

— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/8#issuecomment-164200832.

bryanerayner avatar Dec 13 '15 05:12 bryanerayner

Can someone please clarify if minification of the TypeScript output is likely to be problematic using tools such as uglify? Some of the files in a project I'm working on seem to minify correctly while others do not.

richmwatts avatar Dec 14 '15 17:12 richmwatts

@richwatts, generally it should not be problematic but sometimes configuring the uglify is bit unpalatable. I recently had issues with jQuery and some other (non-AMD) plugins in the mix. I was using gruntfile.js to produce single minified file. Here is the how the configuration looks like:

(gruntfile.js in the root of simple 'website' project)

/// <binding ProjectOpened=uglify/>

// the above line is produced & parsed by VS2015's Task Runner Explorer for
// binding the grunt/node.js task with EnvDTE events.

module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt); 
  var jsBinBase = 'assets/bin/'; 

  grunt.initConfig({
    uglify: { 
      options: { 
        compress: true, 
        mangle: { 
          except: ["$super"], 
          toplevel: true 
         }, 
        sourceMap: true 
       }, 
       target: { 
         src: [ // mixed sources, AMD and non-AMD
           'assets/js/rickshaw/vendor/d3.v3.js',  // needs to be in order
           'assets/js/jquery-2.1.1.js', // needs to be in order
           'assets/js/jquery-ui/jquery-ui.js',  // needs to be in order
           'assets/js/**/*.js', // include all js files generated by tsc or otherwise
           '!assets/bin/**'  // this is exclusion
         ], 
         dest: jsBinBase + 'app.min.js' 
       } 
     }
  });

  grunt.registerTask('default', ['uglify']);
};

(package.json side by side with grunt.js)

{ 
   "version": "0.0.1", 
   "name": "Dummy", 
   "private": true, 
   "devDependencies": { 
     "grunt": "^0.4.5", 
     "grunt-contrib-uglify": "^0.11.0",
     "load-grunt-tasks": "^3.3.0" 
  } 
} 

As you can see, i had to hand pick some dependencies in targets to make it work. But in case you are using everything-AMD, you wouldn't need to care about the targets order.

If you have similar setup, you can generate the combined output from tsc with source maps and then in the above grunt example change sourceMap: true to sourceMap: 'path/to/your-output.js.map'. With that, uglify will generate mapping between min file and the actual ts file (not just min.js to js), which comes handy when debugging with browser dev tools.

am11 avatar Dec 14 '15 18:12 am11

@richwatts, uglify will not minify private methods.

NoelAbrahams avatar Dec 14 '15 20:12 NoelAbrahams

@NoelAbrahams, private method has nothing to do with uglify.

Private visibility is a design-time construct; it is enforced during static type checking but does not imply any runtime enforcement. ... TypeScript enforces encapsulation of implementation in classes at design time (by restricting use of private members), but cannot enforce encapsulation at runtime because all object properties are accessible at runtime. Future versions of JavaScript may provide private names which would enable runtime enforcement of private members

He (@richwatts) is not uglifying a "typescript file" but the "typescript output", which is JavaScript file..

ghost avatar Dec 14 '15 21:12 ghost

@jasonwilliams200OK, well yes. I think most people on this forum understand private methods without recourse to a quote.

NoelAbrahams avatar Dec 14 '15 22:12 NoelAbrahams

The point about private methods is, given the following TypeScript

class Foo {

    public myPublicMethod(){
        this.myPrivateMethod();
    }

    private myPrivateMethod(){
    }
}

We get JavaScript output:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.myPublicMethod = function () {
        this.myPrivateMethod();
    };
    Foo.prototype.myPrivateMethod = function () {
    };
    return Foo;
})();

Running the JavaScript output through uglify produces:

var Foo=function(){function t(){}
return t.prototype.myPublicMethod=function(){
this.myPrivateMethod()},
t.prototype.myPrivateMethod=function(){},t}();

This minification is inefficient, because the private method should have been reduced to a single character, say a instead of myPrivateMethod. Doing so would improve minification by 4% for this simple example. Unfortunately, uglify cannot do anything about it (without further annotation) because the TypeScript compiler emits both the private and public methods on the prototype, so that there is no distinguishing between the two.

Those writing JavaScript libraries would typically write their code in such a way as to obtain better minification, for example:

    function Foo() {
    }
    Foo.prototype.myPublicMethod = function () {
        myPrivateMethod.call(this);
    };

    function myPrivateMethod() {
    };

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

So, while using uglify is not "problematic" as such, it will not be as efficient as minification generated by a system that understands private methods, that is, minification generated directly by TypeScript.

NoelAbrahams avatar Dec 15 '15 11:12 NoelAbrahams

^^ yes! Exactly. :)

electricessence avatar Dec 28 '15 22:12 electricessence

@NoelAbrahams, while I agree that TypeScript has better context to improve the compression, the private methods issue you are describing is non-existent with UglifyJS if you use the correct switches:

npm install uglify-js

:: with --mangle-props
.\node_modules\.bin\uglifyjs --mangle --mangle-props -- yourexample.js
var Foo=function(){function o(){}o.prototype.a=function(){this.b()};o.prototype.b=function(){};return o}();
:: ^107 chars

:: without --mangle-props
.\node_modules\.bin\uglifyjs --mangle -- yourexample.js
var Foo=function(){function t(){}t.prototype.myPublicMethod=function(){this.myPrivateMethod()};t.prototype.myPrivateMethod=function(){};return t}();
:: ^148 chars

ghost avatar Dec 28 '15 23:12 ghost