When I use ES6 features like for example template string, arrow functions, destructuring within a TypeScript file. Afterward I pile the file to normal JavaScript ...
Are the ES6 syntax piled too by the TypeScript piler? Or do I have to use an additional piler (Babel)?
When I use ES6 features like for example template string, arrow functions, destructuring within a TypeScript file. Afterward I pile the file to normal JavaScript ...
Are the ES6 syntax piled too by the TypeScript piler? Or do I have to use an additional piler (Babel)?
Share Improve this question asked Nov 24, 2016 at 6:24 cluster1cluster1 5,7647 gold badges38 silver badges59 bronze badges 3- use babel for es6 – Anmol Mittal Commented Nov 24, 2016 at 6:29
-
It depends - see
--target
piler option. – artem Commented Nov 24, 2016 at 6:31 -
2
Yes, they are, if proper
target
is specified. Some of them are supported fores5
only in recent versions (async
function) or aren't supported at all (new.target
) – Estus Flask Commented Nov 24, 2016 at 6:31
2 Answers
Reset to default 8Are the ES6 syntax piled too by the TypeScript piler? Or do I have to use an additional piler (Babel)?
I disagree with the Fylax's answer. The TypeScript piler doesn't require an additional tool for converting the ES6 syntax to ES 3 or 5.
The TypeScript piler tranpiles the new syntax (let
, for … of
, arrow functions, rest parameters, etc.) to ES 3 or 5. But it doesn't provide any polyfill by itself. In order to use a recent API (like Promise
) on a old VM ES 3 or 5, you have to:
- Load a polyfill (like es6-promise) that makes the API available;
- Say the piler to use the standard typings for this API.
It is a robust design option. With typeScript, you have to choose carefully the polyfills you need, and to test them on the different browsers you target.
By default, when the target is ES 3 or ES 5, the piler doesn't use the definitions for the recent ECMAScript API. See the documentation:
Note: If
--lib
is not specified a default library is injected. The default library injected is:► For
--target ES5
:dom,es5,scripthost
If a polyfill makes an API available, then we can configure the piler to use it. Here is an example of configuration file tsconfig.json
for using promises on ES5 VM:
{
"pilerOptions": {
"target": "es5",
"lib": ["dom", "es5", "es2015.promise"]
}
}
However, Babel can convert a few more features to ES 5 than TypeScript does. See the patibility table from Kangax.
You need additional pilers that downport your code from ES6 to ES5.
TypeScript is pretty smart and will do most of the work for you (i.e. translate let
to var
or arrow functions to standard functions with right scope and bindings).
EDIT: as @Paleo pointed out, on 99% you don't need any external piler as you can provide to TypeScript an extra library (polyfill) which makes everything work fine.
You will need an extra piler on very rare cases when you are not covered neither by transpiler nor by polyfill's.