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?)
What @evmar says is correct. It was an experiment and never used in production. Looking back at it now, I am convinced that using TS types for making optimization decisions is not worth the trouble. There are two main reasons:
- it is too painful to debug misoptimized applications and in big programs TS types are not correct with the fidelity needed for these painful scenarios to not occur too often.
- Structural types allow for very easy flow of concrete objects through abstract types (think interfaces). An optimizer wants to connect the concrete object creation with the concrete usage site, but the TS type-checker will not directly give it that information. An optimizer will have reconstruct a lot of information through a global walk through the whole program. At that point the optimizer starts to look like a Hindley-Milner type-inferencer for a stricter type system. It is not clear to me what have we gained by using the TS types.
Here is an example for 2)
interface I {a: string, b: string};
interface I2 {a: string};
const x: I = {a: '', b: ''}; // construction site
function f(x: I2) {
x.a; // usage site
}
f(x);
The optimizer needs to know whether a: '' is ever used, so it needs to find x.a in f but that has to go through all f call-sites. The abstract types I and I2 don't make that easier, as one has to find all assignability points, i.e. knowing that f(x) exists and that I does get assigned into I2. Add generics into this mix and hopefully you are terrified.
I have a longer write up that is not ready to be shared, but my personal conclusion is:
Types tend to become a synonym for any static analysis. However, type systems are designed with certain use cases in mind. The TS type system is designed for ease-of-use and unobtrusiveness to JS developers. Making use of the TS types for optimizations is a major stretch of the original intent, and it is not clear whether optimizers would be better served by starting from scratch (code without types).
Caveat here being that this is all separate from using the TS toolchain - AST, transformers for optimizations. Those can be great to reuse.
I hope ppl in Microsoft are better than ppl from Google at cutting corners and killin two rabbits in one shot: provide minification capability and keep it bug/undefined behaviour -free <3 high hopes energy here
Dont worry about waiting for this support to be available cuz it will be a long time wait.
Instead go with npm package or angular whatever webpack/aot to do thr javascript minification for you. Thats what we did w/ the npm package & added this short command script to get this job done instead of waiting for it
On Wed, Nov 20, 2019, 10:38 PM Victor Mus [email protected] wrote:
I hope ppl in Microsoft are better than ppl from Google at cutting corners and killin two rabbits in one shot: provide minification capability and keep it bug/undefined behaviour -free <3 high hopes energy here
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/microsoft/TypeScript/issues/8?email_source=notifications&email_token=ABHAL6PKAJ726D3PE2GNQCDQUX7B5A5CNFSM4ARVTRS2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEEY3IZA#issuecomment-556905572, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABHAL6PUYT35HX2VBK5URJTQUX7B5ANCNFSM4ARVTRSQ .
Using TypeScript type information to get better minification is a large discussion with many potential avenues and pitfalls. @rkirov's I / I2 example is a great example and indeed if I try to use VS Code to rename a, it fails to rename all the instances and you end up with compile errors! If VS Code doesn't get it right on a single symbol, it's unlikely a minifier would get it right on a whole codebase!
But that doesn't mean type information isn't useful. There are things that UglifyJS doesn't do or doesn't do well, that I think can be improved with type information. In particular, I'm interested in property renaming. UglifyJS doesn't enable this by default and the docs say "Note: THIS WILL PROBABLY BREAK YOUR CODE".
But property renaming isn't hard for the reason @rkirov highlighted. The way it works in Closure and UglifyJS, etc. is properties are renamed globally. This is a "clever" trick that means in the I / I2 example, it'll just automatically rename all instances of a to the same thing even though the minifier has no idea if I and I2 are related or not. It just sees a and replaces it with xyz123 or whatever.
This is a reasonably safe way to rename properties since you're guaranteed that all usages of property a will be renamed to the same thing regardless of where they appear. It's probably slightly non-optimal (since you need to rename onto globally unique names even if they're never used in the same context) but that's not that big of a concern.
The (main) challenge with existing property renaming (and the reason UglifyJS says it will break your code and Closure has a long list of dangers / workarounds when enabling advanced optimizations) is that it's only safe if your code exists in a vacuum with no interaction with other APIs (e.g. the DOM, other SDKs, etc.) or services (e.g. REST calls to your backend). It's safe to rename MyApp.document but not window.document and it's safe to rename MyMessage.text but not text in let databaseRequest = { text: '...' }.
NOTE: This isn't the only challenge. JS has lots of dynamic ways of accessing properties, etc. If you do x['te' + 'xt'] the minifier probably won't know that you are accessing x.text which might have been renamed. But you can avoid most of these via reasonable coding conventions (and a TypeScript minifier could notice / warn you when you're doing problematic things like this).
So you you need some sort of heuristic approach to figure out what's safe to rename (i.e. it's 100% internal to your app/library) and what's not (i.e. it crosses the boundary into the outside world). A simple solution is to use naming conventions (e.g. only rename properties that you've prefixed with _). But that pollutes your codebase and requires ongoing manual auditing. It would be better if perhaps you were only forced to use naming conventions for exceptional cases where the builtin heuristics don't work automatically.
And here's the thing. TypeScript types give you a lot of extra information to build your heuristics on. window is of type Window which comes from lib.dom.d.ts which is external to your app. So you can't rename any properties on it. If databaseRequest is passed to SuperDB.write() which is defined in a super-db.d.ts file from an external npm package, it's probably not safe to rename properties on it either.
Is it foolproof? No. Is it better than UglifyJS can do without types? Absolutely. It'll probably end up being roughly equivalent to what Closure does (where you use externs to declare what's external to your app, etc.) but given the rich type information that exists for TypeScript (minimal use of any, comprehensive d.ts files, etc.), it should require less manual tweaking. And even if it ends up equivalent to Closure, Closure is a beast to deal with and not very user-friendly.
So I think there's a big opportunity to get Closure-level minification but with less effort (due to better type information) and a better developer UX.
Would it be a valid argument to say tsconfig should include a minify option simply to allow decoupling from another tool (for example, gulp)? We currently have a project using typescript that is using gulp and npm only for the purpose of javascript minification. If tsconfig had a minify option, then we'd be able to completely break our project free from gulp and the npm ecosystem.
I also want to use Typescript for minification to free me from Nodejs.
2020, The TypeScript is static language - cannot remove unused code..
I was starting to love TypeScript, but then I discovered that the compiler does not support any optimization nor dead code removal. There are many things that it could optimize thanks to its knowledge about... Well, types! Think of constant propagation.
Oh, and finally there's a reason that IMHO makes the effort worth by itself: not involving the usage of a complex, multi-step build pipeline that could break in many different points. If there is a bug caused by your code generation process you have to look at typescript, not at bundler+loader+typescript+various_plugins.
@falcon03 I mostly agree with you, but I'm not sure if optimization can be thrown in the same bin as minification (even optimization might reduce code size).
For constant folding/propagation, you might want to look at #3964 which discusses the topic. Unreachable/dead code removal on the other hand could be detected by the IDE and shown to the user (maybe also by the compiler as warning), but not emitting does not seem to be a safe approach to me, for instance if one adds some safety net for when the type passed into a call is not what the compiler knew at compile time.
Hi there,
if you're looking for property renames optimizations (for instance like google closure compiler does in advanced mode) you can try https://github.com/timocov/ts-transformer-properties-rename - it's the next generation of ts-transformer-minify-privates from https://github.com/microsoft/TypeScript/issues/8#issuecomment-500379375, but this one might detect all internal properties and rename them as well.
@falcon03 I’ve been using bundlers, transpilers, typescript, uglifiers, loaders, webpack plugins for 5+ years. The number of times I had to do any debugging for the purpose of figuring out why the output is wrong due to a bug is... 1 (literally one). And that was when I was experimenting with experimental ES6 minifiers 3 years ago and Safari 10 had a bug with a certain ES6 syntax, it wasn’t a bug with my pipeline apparently.
Just saying.
AssemblyScript already emits the most minified, non-human-readable code that a TypeScript compiler should ever need to, and from what I hear, It's well-optimized too!
No, it's not TypeScript, it's a subset, but that might change as time goes on.
By minifying TSC output, the TS developers essentially encourage the misusage of JavaScript as a compilation target. At minimum, one should target asm.js, but it has been deprecated in favor of Wasm.
This is probably worth closing and saying that TSC removes bugs and headaches, not whitespace; that is already a very important feature that we are all grateful for ❤️.
The TypeScript development team should focus on TypeScript. Minification, optimization, and related issues should be taken on by the community, by using the syntax and type output API that TSC already offers.
AssemblyScript already emits the most minified, non-human-readable code that a TypeScript compiler should ever need to, and from what I hear, It's well-optimized too!
I really like the way you look into this issue. The JS target of AssemblyScript uses types to produce the runtime optimized code.
For example,
let x: i32 = foo()
is compiled to the following which hints V8 to optimize this code for integer types instead of floating-point numbers.
let x = foo() | 0
Feeding the produced code to Terser (or other minifies) can further reduce the size.
I actually raised this once in one of the discussions with the core team of AssemblyScript. For me, the reason that the JS target is useful is that DOM API is still missing in WASM, and so WASM does not completely replace JavaScript yet.
There are still some things to improve in the JS target. For example, I had some concerns with reusing the modules produced this way (e.g. if the modules are ES6 compliment, etc), or if all the generated code (like globals) are needed for JS target.
cc: @maxgraey @torch2424
@aminya
...The JS target of AssemblyScript uses types to produce the runtime optimized code.
is compiled to the following which hints V8 to optimize this code for integer types instead of floating-point numbers.
let x = foo() | 0
Not only does that hint ES implementations/runtimes to use 32-bit integers, but it also forces them to. For example, if foo were an imported JS function, that would coerce the result into an int.
This also ensures that the runtime semantics of AS are preserved. Let's say that the JS function foo was defined as:
const foo = () => 0xffff * 0x10000;
This would result in an overflow, but now the AS generated JS would have the same behavior as the Wasm.
There are more interesting cases, such as i64, how do they handle that? 64-bit integers would have to represented as JS BigInts in order to maintain precision.
I actually raised this once in one of the discussions with the core team of AssemblyScript. For me, the reason that the JS target is useful is that DOM API is still missing in WASM, and so WASM does not completely replace JavaScript yet.
Of course not, Wasm doesn't replace JS, at least not yet. It was originally intended that authors would write parts of their code in normal JS, and performance-critical parts in asm.js. Now Wasm replaces asm.js, but they still fill the same role.
But, with the newer interfacing types proposals and such, it's not infeasible to imagine a Wasm controlled front-end web. When Wasm has native access to WebIDL types, you can expect quite a change.
But in the meanwhile, someone at AS should try to mimic Rust Wasm Bindgen's ABI. It gives some access over JS, while the control flow primarily still remains in Wasm. Differentiating between JS objects and Wasm objects may get complicated, they may need to introduce a type-level API to allow this type of functionality.
@RyanCavanaugh 👋 Hi there I am working on a command-line wrapper for typescript which will minify the code in the output file with the uglifyjs library I will release it soon.
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?)
Okay I got it
@aadityasivaS can you please consider terser instead of uglifyjs?
@aadityasivaS can you please consider terser instead of uglifyjs?
okay
@RyanCavanaugh 👋 Hi there I am working on a command-line wrapper for typescript which will minify the code in the output file with the uglifyjs library I will release it soon.
To be clear, the output file is javascript and can already be processed by many different tools. This issue is about minifying during the Typescript compilation itself using information that only Typescript has.
Do you have some way of capturing and using the Typescript metadata with the other minifier tooling? Otherwise just running uglify/terser on the output is not the solution.
@RyanCavanaugh 👋 Hi there I am working on a command-line wrapper for typescript which will minify the code in the output file with the uglifyjs library I will release it soon.
To be clear, the output file is javascript and can already be processed by many different tools. This issue is about minifying during the Typescript compilation itself using information that only Typescript has.
Do you have some way of capturing, transferring, and using the Typescript metadata with the other minifier tooling? Otherwise just running uglify/terser on the output is not the solution.
oh okay anyway thanks