
Code transpiling
Browsers, as we all know, only work with JavaScript, they don't understand TypeScript. We hence need a mechanism to convert our TypeScript code into plain JavaScript (ES5 is our safest bet). The TypeScript compiler does this job. The compiler takes the TypeScript code and converts it into JavaScript. This process is commonly referred to as transpiling, and since the TypeScript compiler does it, it's called a transpiler.
When transpiling code from TypeScript to JavaScript, we can specify the flavor of JavaScript to use. As mentioned earlier, ES5 is our safest bet, but if we plan to work with only the latest and greatest browsers, go for ES2015. For 7 Minute Workout, our code to transpile to is ES5 format. We set this TypeScript compiler configuration in tsconfig.json (see the target property).
Interestingly, transpilation can happen at both build/compile time and at runtime:
- Build-time transpilation: Transpilation as part of the build process takes the script files (in our case, TypeScript .ts files) and compiles them into plain JavaScript. Angular CLI does build-time transpilation.
- Runtime transpilation: This happens in the browser at runtime. We directly reference the TypeScript files (.ts in our case), and the TypeScript compiler, which is loaded in the browser beforehand, compiles these script files on the fly. This is a workable setup only for small examples/code snippets, as there is an additional performance overhead involved in loading the transpiler and transpiling the code on the fly.
The process of transpiling is not limited to TypeScript. Every language targeted towards the web, such as CoffeeScript, ES2015, (yes JavaScript itself!) or any other language that is not inherently understood by a browser needs transpilation. There are transpilers for most languages, and the prominent ones (other than TypeScript) are tracuer and babel.
The Angular CLI build system takes care of setting up the TypeScript compiler and sets up file watchers that recompile the code every time we make changes to our TypeScript file.
Let's get back to the app we are building and start exploring the code setup.