DEV Community

agrem28
agrem28

Posted on

Transpilers

Transpilers are wonderful tools for programmers. Code can be translated from one language to another. It can even be converted from one syntax or version to another. It can be useful in many different ways. It allows the programmer to always be able to code in his or her preferred language. Some
libraries and frameworks are incompatible with browsers as well, such as React, which is one of the most popular app frameworks available. Just load the files that are written in your preferred style into a transpiler. The output file can then be used as the reference script and tucked away into a dist folder while you focus on your own code.

Alt Text

In the above example, the code on the left is hand-written JavaScript in ES2015 format. The code on the right is code generated from a transpiler which is in ES5 format. Some browsers still do not recognize some ES2015 syntax, so it is useful to convert it to older versions which are universally accepted.

Implementation

Now that we understand why we use transpilers, it's useful to understand how they work. Work is accomplished in three distinct steps: parsing, transformation, and generation. Here is a nice graphical representation.

Alt Text

Parsing

Parsing is the process of the transpiler reading the code and interpreting that code. That interpretation is represented by an abstract syntax tree, which is a tree whose nodes represent actions or data in the program such as conditions and assignments.

Alt Text

The above image shows a short function and the corresponding AST. You can see that leaf nodes are used for variables and constants while branching nodes represent either operators or flow. By traversing the tree you can see the path the code will take in its execution.

Transformation and Generation

The nodes are then translated into equivalent nodes in the target language. This is done because it is easier for the transpiler to convert individual nodes instead of raw code.
This process may take one or many steps to complete, depending on the complexity and size of the code.

Once this is done, the final step is the new code generation. This is typically the easiest and quickest step because it is the simple matter of traversing the nodes of the tree and outputting the correct code.

After that, the new code will be stored on a new file which can be saved within your program and referenced as the main script. Some useful transpilers available for free use include:

  • Babel, a JS transpiler for converting from ES6 to ES5
  • Traceur, another similar JS compiler
  • Opal, a Ruby to JS compiler
  • TypeScript, a syntax more in line with an OO language like Java, but acts like JS
  • CoffeScript, a syntax similar to Python, but acts like JS

There are many more which can meet a variety of needs. Try them out and see how your work will be made much easier!

Top comments (0)