Understanding JavaScript Compilation

Rate this content
Bookmark

Compiling (or transpiling) modern JavaScript to older ECMAScript-compatible versions has allowed the web to evolve incredibly fast while making us happier developers. But how does the compilation process work? How can we write our own Babel plugins? Let's find out!

This talk has been presented at Node Congress 2022, check out the latest edition of this JavaScript Conference.

FAQ

Babel is a JavaScript compiler that takes modern JavaScript code and transforms it into a version that is compatible with older browsers and environments. It allows developers to use newer syntax and features in JavaScript without worrying about support issues in older runtimes.

The visitor pattern is a way of separating an algorithm from the object structure it operates on. In JavaScript tooling, such as Babel and ESLint, the visitor pattern allows developers to define operations to perform on certain nodes of the abstract syntax tree without modifying the tree itself. It's useful for implementing transformations and code analysis.

A simple example of code transformation using Babel is converting 'var' declarations to 'let'. For instance, if the input code is 'var foo = 10;', Babel can transform it to 'let foo = 10;' as part of making the code more modern and adhering to current JavaScript best practices.

JS CodeShift is a toolkit built and maintained by Facebook for running codemods, which are scripts used to make automated code changes. It is particularly useful for large-scale JavaScript refactors, allowing developers to programmatically apply changes across a codebase, such as renaming variables or updating APIs.

An Abstract Syntax Tree (AST) is a tree representation of the structure of source code. Each node of the tree denotes a construct occurring in the source code. The AST outlines the syntactic structure of the code and is used during the code transformation phase of compilation to make specific modifications to the code.

The three main phases of JavaScript compilation include parsing, code transformation, and code generation. Parsing involves breaking down the code into tokens and creating a parse tree. During code transformation, the abstract syntax tree (AST) is modified according to specific rules. Finally, code generation produces the transformed source code.

Transpilation in JavaScript refers to the process where source code written in one language or version is transformed into another version of JavaScript that can be executed in environments that do not support the original form. Unlike traditional compilation that produces binary code, transpilation converts code from one source language to another source language.

Michele Riva
Michele Riva
8 min
18 Feb, 2022

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Today's Talk explores the concepts of compilation and transpilation in JavaScript, highlighting the three steps involved: parsing, code transformation, and code generation. The process of traversing an abstract syntax tree is discussed, with examples of tools like Babel and ESLint that can be used for code transformations. Code transformation tools and techniques, such as CodeShift and T-TypeScript plugin, are introduced, emphasizing the power of abstract syntax trees and the visitor pattern. The summary concludes by encouraging further exploration of code refactoring and transformations using tools like Babel, TSLint, and astexplorer.net.

1. Understanding JavaScript Compilation

Short description:

Today, we are going to be talking about compilation, or I should say transpilation. In fact, when talking about compilation, we refer to that process that takes a source code as an input and produces binary code or bytecode as an output. The whole compilation phase takes place in three different steps. Parsing, code transformation, and code generation.

♪♪♪ Hello, everyone, and welcome to my talk, Understanding JavaScript Compilation. Before we start, let me introduce myself briefly. I'm Michele Riva, Senior Architect at NearForm, author of Real World Next.js book, Google Developer Expert and Microsoft MVP.

Today, we are going to be talking about compilation, or I should say transpilation. In fact, when talking about compilation, we refer to that process that takes a source code as an input and produces binary code or bytecode as an output. In JavaScript, we are more likely to adopt transpilation. An example is the REST script compiler, which takes correct REST script code as an input and produces proper JavaScript code as an output. So from one source code to another. We can do the same with Babel, for example. In that example, we have the optional chaining and nullish operators, which are not supported on older runtimes and browsers. We want to make this code more compatible, so we take this source code, we feed the Babel compiler, and we get the following code as an output which is still valid JavaScript source code, which is more compatible with older runtimes.

The whole compilation phase takes place in three different steps. Parsing, code transformation, and code generation. Let's break them down. Step number one for parsing is tokenization. So we have var foo equals 10, and we divide it into separate tokens, var foo equals 10. And then we can create a parse tree. And here we can see the structure of our program and understand if it's correct or not. And the next step would be abstract syntax tree creation. So it's quite difficult to understand from these slides, so let me go on the other one. Okay, so this is how it's presented. We have variable declarations at the top. And again, JavaScript can create multiple variables in a row. In that case, we create just one variable. So, we will be ending up having just one variable declaration. So, var foo equals 10, it's the variable declaration. We can break it down to all the variable declarations we have. In that case, just one. So, variable declarator, where we declare that foo, it's equal to 10. We can break down the variable declarator again in two different parts, the identifier, foo, and numeric literal, which is 10.

2. Understanding Abstract Syntax Tree Traversal

Short description:

If we were writing like foo equals true, we would have wrote down the boolean literal instead of the numerical one. When reading an abstract syntax tree, we call this process traversing the tree. With Babel, we can transform variable declarations from var to let. The same concept applies to other tools like Prettier, ESLint, Babel, GIS, CodeShift. With ESLint, we can report and fix errors related to template literals.

If we were writing like foo equals true, we would have wrote down the boolean literal instead of the numerical one, or strings or whatever, just for you to understand. While it's quite easy to understand this tree, I guess, this one, it's a bit more challenging to deal with.

When reading an abstract syntax tree, we call this process traversing the tree. It's quite complex on, of course, complex programs. But luckily, many tools such as Babel, ESLint, Pretier, provides us a nice interface for traversing the tree which is called the visitor pattern.

In that case, with Babel, we're saying, okay, dear Babel, please give me all the variable declarations or the identifiers, all the numerical literals, and we just print them to the console. Once we get, for example, all the variable declarations, we can start transforming them. So that's the case. We say, okay, please give me all the variable declarations inside of our code. And if the kind of the variable is a var, just transform it into a let, which is not wise. I'm not suggesting you're doing that, but it's a very straightforward example. So that makes things easier for us. So that said, on the left, we have our input var foo equals 10. And on the right, we have our output let foo equals 10. As you can see, on line two, we have constant and we leave it untouched because it's not a variable, it's a, it's a const. So as you can see on the code, we are not saying if it's constant, please change it to let. So we are not doing that. As I said, the same concept applies to other tools, such as Prettier, ESLint, Babel, GIS, CodeShift. And we're gonna see them in details right now.

With ESLint, we have a similar approach. We say, okay, please, ESLint, give me all the template literals you can find in my code. And if I find one, I can report to ESLint an error, such as please do not use template literals. And I can also provide a fix for it. But in that case, if I have an expression inside my template literals, I can say, okay, I'm too lazy for that. So I'm just returning, I'm not fixing this. But if I don't have an expression, I can say, okay, so I don't have expression. I don't have any expression. So no dynamic data inside my template literals. So just change the literals into double quotes. So that's what we are doing now.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
Watch video: Debugging JS
Debugging JavaScript is a crucial skill that is often overlooked in the industry. It is important to understand the problem, reproduce the issue, and identify the root cause. Having a variety of debugging tools and techniques, such as console methods and graphical debuggers, is beneficial. Replay is a time-traveling debugger for JavaScript that allows users to record and inspect bugs. It works with Redux, plain React, and even minified code with the help of source maps.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
The talk discusses the importance of supply chain security in the open source ecosystem, highlighting the risks of relying on open source code without proper code review. It explores the trend of supply chain attacks and the need for a new approach to detect and block malicious dependencies. The talk also introduces Socket, a tool that assesses the security of packages and provides automation and analysis to protect against malware and supply chain attacks. It emphasizes the need to prioritize security in software development and offers insights into potential solutions such as realms and Deno's command line flags.
Webpack in 5 Years?
JSNation 2022JSNation 2022
26 min
Webpack in 5 Years?
Top Content
In the last 10 years, Webpack has shaped the way we develop web applications by introducing code splitting, co-locating style sheets and assets with JavaScript modules, and enabling bundling for server-side processing. Webpack's flexibility and large plugin system have also contributed to innovation in the ecosystem. The initial configuration for Webpack can be overwhelming, but it is necessary due to the complexity of modern web applications. In larger scale applications, there are performance problems in Webpack due to issues with garbage collection, leveraging multiple CPUs, and architectural limitations. Fixing problems in Webpack has trade-offs, but a rewrite could optimize architecture and fix performance issues.

Workshops on related topic

Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Top Content
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Node.js Masterclass
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Matteo Collina
Matteo Collina
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
Build and Deploy a Backend With Fastify & Platformatic
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Matteo Collina
Matteo Collina
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.