0
votes

I have a project with javascript codebase. I would like start gradually shifting to typescript and also ensure that the existing javascript code stays on ES5 level. I.e. safeguard that ES6 features would be transpiled to ES5.

I thought that this could be solved by introducing just tsc to the build chain. The tsconfig.json has target for ES5 and tsc is set to process both typescript ja javascript files.

But appararently tsc does not transpile javascript files to ES5 level. Or am I missing something in my setup?

My guess is that I still need to add babel for the build chain to ensure that all code going to be executed in browser is at ES5 level.

Simple example below:

tstest.js containg ES6 feature:

var arr = ["a", "b", "c"];
console.log(arr.includes("b"));

Transpiling is not happening for javascript:

/tmp> tsc -t ES5 -allowJs -outDir ./transpiled tstest.js
/tmp> cat transpiled/tstest.js
var arr = ["a", "b", "c"];
console.log(arr.includes("b"));
1
Have you added the ES7 lib into your tsconfig file? According to this thread: github.com/Microsoft/TypeScript/issues/2340 you need to include the library "es7" and "dom". If you have added these, please add the tsconfig file in your question.hagner
TypeScript doesn't add any polyfill. You have to add in your project the polyfill of your choice for includes.Paleo
@hagner, I tried to add lib definitions now too but it did not still do transpilation. I think the libs are needed for .ts files and what is allowed thereiaarnio

1 Answers

0
votes

Found it out now. Array.includes in ES2016 feature and was therefore not transpiled. E.g. arrow functions are transpiled corrently to ES5 level even in javascript sources:

/tmp> cat tstest.js
const f = a => 2 * a;
console.log(f(5));

Results after tsc:

/tmp> tsc -t ES5 -allowJs -outDir ./transpiled tstest.js
/tmp> cat transpiled/tstest.js
var f = function (a) { return 2 * a; };
console.log(f(5));