简体   繁体   中英

Typescript target not affecting source javascript files (with allowJs)?

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. Ie 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"));

Found it out now. Array.includes in ES2016 feature and was therefore not transpiled. Eg 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM