Search code examples
typescriptgoogle-closure-compileres6-modulestsickle

Closure Compiler + Typescript


I want to use Typescript and then Closure Compile (advanced compilation) to target ES5 and minify the output.

Do I have to use tsickle in place of tsc? It lacks support for all the options tsc has, and is far ambitious in that it wants to translate Typescript types to Closure types (which are not 100% compatible). I don't really need to use Closure types; I just need minification/property renaming.

Can I use tsc to compile Typescript to ES6 modules and use Closure Compiler to minify those (without type checking or type-based optimzations)?

Bonus: Does this answer change if I want to use Closure Library?


Solution

  • Technically, you can take ES6 output from tsc and pipe it immediately to Closure Compiler, as the latter is spec'ed to accept JS as input. We do this already in many places, eg. Angular apps compiled with closure compiler take the rxjs library distribution and include it in the closure bundle. See https://github.com/angular/closure-demo

    In practice, we find a few reasons to use something like tsickle to transform the JS before Closure sees it.

    • enums emit doesn't work in Closure (or rollup IIUC)
    • Closure has some limitations with ES6, for example it currently doesn't support export * - tsickle re-writes that to export {each, visible, symbol}
    • adding JSDoc annotations helps closure understand the structure of the code which can improve optimizations and reduces the number of warnings it prints.

    Our current plan is to decompose tsickle into multiple TS 2.3 emit transforms, then we can be more clear which transforms actually need to be enabled in the compiler.

    Adding types is optional. If you turn off tsickle's typed mode, we'll just print {?} for the types instead. However, if you ever want to use TypeScript's output from closure JS code, then you'll want the closure type-checker to know the types.

    If you're game for a new build tool, we will build tsickle into the Bazel toolchain in https://github.com/bazelbuild/rules_typescript at some point. In the meantime you can file a feature request for Tsickle's main to support more of the command-line flags. (But I think Lucidchart already maintains a fork of Tsickle?)