Transpilers, or source-to-source compilers, are tools that read source code written in one programming language, and produce the equivalent code in another language that has a similar level of abstraction. A good example of transpiler is the Typescript transpiler, which converts Typescript code to JavaScript. Babel transpiler can also be used for ES6 JS code to ES5 JS code.
Whereas compilers also convert the code from one language to other language but both languages are very different in abstraction level. e.g. .java
to .class
file compilation.
ES6 vs ES5
To understand transpiler, you must understand first the difference between ES6 and ES5 JavaScripts. ES6 (ECMAScript 6) is specification for next version JavaScript. Some of its major enhancements include modules, class declarations, lexical block scoping, iterators and generators, promises for asynchronous programming, destructuring patterns, and proper tail calls.
Features are great but most browsers do not support this specification till date. So any UI application, written with ES6, spec will not run in most browsers. To run these applications, this ES6 sourcecode must be converted to supported JavaScript version ES5. ES5 is supported is almost all the browsers and is most stable version till date.
ES6 – Brings ‘types’ to JavaScript. Bring it closer to strongly typed languages such as Java, C#. Most browsers do not support it till date. It must be converted to ES5 to be executed in browsers.
ES5 – Vanilla JavaScript which we have been writing all these years.
Transpiler
A transpiler is a compiler like program, which convert ES6 JavaScript code to ES5 JavaScript code so that it can run in browsers. When the transpiler sees an expression that uses a language feature that needs to be translated, it produces a logically equivalent expression. The produced expressions can be very similar, or very different from the source expression.
What Transpiler Does?
ES6 code => ES5 code (or even ES4, ES3 as well)
Transpiler config for typescript is given in tsconfig.json
file.
{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] } }
Transpiler Demo
Lets see how a ES6 ro ES5 transpile works. Create a file helloworld.ts
and write this code in it.
ES6 Code
export class HelloWorld { constructor() { console.log('welcome'); } };
ES5 Code
To compile typescript code to javascript code, use command “tsc helloworld.ts
“. It will generate helloworld.js
file in same folder.
"use strict"; exports.__esModule = true; var HelloWorld = /** @class */ (function () { function HelloWorld() { console.log('welcome'); } return HelloWorld; }()); exports.HelloWorld = HelloWorld;
Drop me your questions in comments section.
Happy Learning !!
Ask Questions & Share Feedback