Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

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.

JavaScript as a language has evolved over the years with every new version adding new features/capabilities to the language. The latest avatar, ES2015, succeeds ES5 and is a major update to the language. While released in June 2015, some of the older browsers still lack support for the ES2015 flavor, of JavaScript making its adoption a challenge.
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.

If you are new to TypeScript, remember that TypeScript does not depend on Angular; in fact, Angular has been built on TypeScript. I highly recommend that you look at the official documentation on TypeScript ( https://www.typescriptlang.org/) and learn the language outside the realms of Angular.

Let's get back to the app we are building and start exploring the code setup.