Why use babel-loader with ts-loader?
Asked Answered
C

1

60

There is a TypeScript, Babel, React, and Karma Sample.

The Webpack config contains babel-loader with ts-loader for .tsx? files.

Please explain why it is needed? Why isn't ts-loader enough?

Counterscarp answered 3/4, 2018 at 7:8 Comment(0)
T
98

ts-loader: convert typescript (es6) to javascript (es6)

babel-loader: converts javascript (es6) to javascript (es5) and Typescript doesn't do polyfills, which babel does. If you write client-side code in es6 and want it to run on modern browsers, you'd probably need babel's polyfills.

It is less justified with server-side code - just use the latest node version for es6 support. But babel still provides some goodies that tsc doesn't - like caching, or a huge range of plugins that can be very useful.

It's not necessary but a practice for using them all together.

Traps answered 3/4, 2018 at 7:32 Comment(7)
As far as I know we use babel-polyfills manually. Isn't it? Can you show example of using huge range of plugins that can be usefull for typescript files?Counterscarp
Also 'target' option in compiler options of tsconfig can be es5. So you are wrongCounterscarp
@Counterscarp She's not wrong. You need ES6 modules to do tree-shaking.Latricelatricia
But please wait. There is module option in tsconfig. If I specify target: es5 and module: es6 it will produce es5 code with es6 modules. I can't check if for now. But I think it should work. How do you think?Counterscarp
@Counterscarp i think it should work but there's a need to use non-compliant features that aren't supported by TypeScript (usually there's none).UglifyJS doesn’t support the new language features of Javascript (aka ES2015 and above) yet. We need Babel to transpile our code to ES5 and then use UglifyJS to clean up the unused code.Traps
I don't understand. Our goal is to transpile code to ES5 except modules. Babel gives such possibility. If we can achieve the same result with using only typescript config, why do we should to use babel?Counterscarp
Babel 7 can now transpile TS to JS with the babel-preset-typescript and TS only handles type-checking. github.com/Microsoft/TypeScript-Babel-StarterMoraceous

© 2022 - 2024 — McMap. All rights reserved.