The Superpower of ASTs: How We Saved 16% on Our Bundle Size

Rate this content
Bookmark
Slides

Discover the untapped potential of Abstract Syntax Trees (ASTs) in this transformative session. Learn how we achieved a remarkable 16% reduction in our bundle size by inlining constant objects directly into the referencing code, eliminating the need for large files in the output. This method even outperforms Terser's tree shaking used by Webpack.

We will cover:

* Introduction to ASTs: What they are and why they’re invaluable.
* Overcoming AST Challenges: How to navigate the difficulties of working with ASTs.
* Best Practices: Proven techniques for effective AST utilization.
* Avoiding Pitfalls: A secret tip to prevent common mistakes.

ASTs are everywhere, and their applications are vast. This session will empower you with the knowledge and confidence to transform your code, revealing when and how to use ASTs for remarkable results.

Join me for an inspiring journey into the world of ASTs and unlock their potential to revolutionize your coding practices!

This talk has been presented at React Day Berlin 2024, check out the latest edition of this React Conference.

FAQ

Omri Lavi discusses how to reduce bundle size for front-end developers using a super tool that leverages ASTs (Abstract Syntax Trees) to optimize code without changing a single line of code.

The tool helps reduce the bundle size of Monday.com's complex client code by removing unnecessary constant file references and inlining actual values, which helps save each kilobyte in a large-scale application with over 300 developers and millions of users.

Tree Shaking didn't work properly because it doesn't handle objects well, leading to many unused constants files being included in the bundle, which increased the bundle size and memory footprint.

ASTs, or Abstract Syntax Trees, are data structures used to represent code. They are used by tools like ESLint, Prettier, and Webpack to read and transform code programmatically, allowing for optimizations like removing unused code.

Monday.com chose Babel for code manipulation because it is popular, flexible, and pluggable, allowing integration into their existing ecosystem without major changes.

Exec tests are a type of integration test where the input is code that is transformed with a plugin, and the output is executed to ensure the plugin updated the code correctly. They are important for verifying that AST-based plugins work as intended and do not introduce bugs.

Best practices include guarding assumptions by throwing errors for unhandled cases, writing exec tests for new scenarios, and following a development lifecycle that includes implementing solutions, guarding assumptions, and ensuring test coverage.

Omri Lavi emphasizes that ASTs are a superpower and should be considered for solving impossible challenges in code optimization, and developers should use the AST development lifecycle to maximize their impact.

The super tool can improve performance by 16% more than Terza's tree shaking, which is considered the state-of-the-art for bundle optimization.

Omri Lavi
Omri Lavi
20 min
16 Dec, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Our story is about a super tool that reduces bundle size without changing code. It removes input statements, improves performance, and reduces bundle size. ASTs are used to optimize constant files by removing references and replacing with values. Bubble is a tool for code manipulation using ASTs. Manipulating code with Bubble paths allows for removing unnecessary variable declarations. Careful handling and testing are necessary when using AST tools. Guarding assumptions and writing exec tests are key practices. Completing the AST development lifecycle ensures correct code updates. ASTs are a powerful tool for software development.

1. Introduction to Bundle Optimization

Short description:

Our story is about a super tool we used to reduce the bundle size without changing any code. It automatically removes 4,250 input statements, improves performance by 16%, and reduces the bundle size by 14 megabytes. As a tech lead at Monday's DevTools group, I build tools for developers to work with higher velocity and confidence. We have a large and complex client code, with over 300 developers and millions of users, so reducing the bundle size is crucial.

♪♪ ♪♪ ♪♪ Take a moment to think what this means to you. So you're probably thinking that this is a bundle, but you're most likely thinking that this is painful, because we, as front-end developers, spend a lot of time and effort on reducing it as much as possible. Our story is about a super tool we used to reduce the bundle size, and it took us from here to there without changing one line of code. What if you, too, could have a super tool that would automatically remove 4,250 input statements while improving your performance by 16% more than Terza's tree shaking, which is considered the state of the art regarding to bundle optimization? Also, it will reduce 14 megabytes from your bundle size, which is really a lot. Hi, I'm Omri Lavi. I'm a tech lead at Monday's DevTools group. This means I'm building tools for developers so they can work with higher velocity and with higher confidence. I'm also part of the Foundations group, so this gives me unique opportunities to work on some really interesting stuff like the one I'll talk about today. To give you some background, at Monday.com, we have a large and complex client code. We have more than 300 developers changing the client code on a daily basis, and we have millions of users, so each kilobyte we save matters a lot. This is why we look for innovative ways to reduce the bundle size as much as possible.

2. Optimizing Constants Files with ASTs

Short description:

We noticed a pattern with constant files that only contained strings and were referenced for one or two values. Tree Shaking didn't work well for objects, resulting in unnecessary JavaScript in our bundle. This increased bundle size, network load, and memory footprint. To solve this, we used ASTs to remove references, replace with actual values, and eliminate imports. ASTs are abstract syntax trees used to represent code. Tools like AST Explorer help visualize and manipulate code programmatically.

And a while ago, we noticed the following pattern. We saw that we have many files that look like this. They exported nested objects that in the end of the day only contained strings. This is why we call them constants files.

And the files that referenced the constants files only used one or two values out of these constants. So you're probably thinking to yourself, okay, I have Tree Shaking exactly for this case, and if you're unfamiliar with Tree Shaking, then it's a very common algorithm that most bundlers use today to remove the unused values from your bundle, so you'll end up exactly with what you need in your bundle. But in our case, Tree Shaking didn't work properly because we used objects, and Tree Shaking doesn't take care well with objects. So we ended up with something like this in our bundle, and you see that all the red parts are actually constants files.

And the problem with that is that we have many constants files inside our bundle. This means we have more JavaScript than what we actually needed. This increased our bundle's size and made it more network-heavy, so our application became heavier to load. Additionally, all of these files were kept in memory and were never removed, so it increased our memory footprint more than what we wanted. And it felt a lot like this. We had a small piece of code that carried a huge luggage with it.

So we had a dream. We had a dream that while we're building the bundle, we'll find the reference values out of the constants files, remove the references, and replace them with the actual values, and then we can remove the import for these constants files and end up exactly with the values that we need inside our bundle. So we knew what we wanted to do, but we weren't sure how to do it. We knew that we wanted to avoid major refactors because we had a lot of code that needed to be updated, and we knew we wanted to avoid manual update of the code because, again, it was a lot of code, and we needed to do it programmatically to avoid errors that humans can do. So after some thinking, we understood we can use ASTs, but wait, ASTs aren't too common, right? Think for a moment if you've ever used ASTs before.

So the truth is that we all use ASTs, and we just may not know it, and we'll see it in a second. So ASTs are abstract syntax trees. It's a data structure used to represent a piece of code, and the best way to understand it is by a tool called AST Explorer. AST Explorer is a free online tool, and you can put a piece of code in it, like the one here, and it will show you its AST. It may seem scary on the first glance. It really is, but the power of AST Explorer is that you can select a piece of code, and it will show you its matching node in the AST. So for example, you can see here we have a string literal node with the value of hey, Berlin. We can also select this part here to see it's a variable declaration node with the name of hi, the value of hey, Berlin, and we can also see its kind is a const. It's important to understand that ASTs really everyone. Many tools use AST. If you think of ESLint, PostCSS, Prettier, Webpack, and many other tools, they all use AST to read and transform code programmatically.

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

A Guide to React Rendering Behavior
React Advanced 2022React Advanced 2022
25 min
A Guide to React Rendering Behavior
Top Content
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize React rendering.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
Watch video: React Concurrency, Explained
React 18's concurrent rendering, specifically the useTransition hook, optimizes app performance by allowing non-urgent updates to be processed without freezing the UI. However, there are drawbacks such as longer processing time for non-urgent updates and increased CPU usage. The useTransition hook works similarly to throttling or bouncing, making it useful for addressing performance issues caused by multiple small components. Libraries like React Query may require the use of alternative APIs to handle urgent and non-urgent updates effectively.
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Today's Talk discusses the future of performance tooling, focusing on user-centric, actionable, and contextual approaches. The introduction highlights Adi Osmani's expertise in performance tools and his passion for DevTools features. The Talk explores the integration of user flows into DevTools and Lighthouse, enabling performance measurement and optimization. It also showcases the import/export feature for user flows and the collaboration potential with Lighthouse. The Talk further delves into the use of flows with other tools like web page test and Cypress, offering cross-browser testing capabilities. The actionable aspect emphasizes the importance of metrics like Interaction to Next Paint and Total Blocking Time, as well as the improvements in Lighthouse and performance debugging tools. Lastly, the Talk emphasizes the iterative nature of performance improvement and the user-centric, actionable, and contextual future of performance tooling.
How React Compiler Performs on Real Code
React Advanced 2024React Advanced 2024
31 min
How React Compiler Performs on Real Code
Top Content
I'm Nadia, a developer experienced in performance, re-renders, and React. The React team released the React compiler, which eliminates the need for memoization. The compiler optimizes code by automatically memoizing components, props, and hook dependencies. It shows promise in managing changing references and improving performance. Real app testing and synthetic examples have been used to evaluate its effectiveness. The impact on initial load performance is minimal, but further investigation is needed for interactions performance. The React query library simplifies data fetching and caching. The compiler has limitations and may not catch every re-render, especially with external libraries. Enabling the compiler can improve performance but manual memorization is still necessary for optimal results. There are risks of overreliance and messy code, but the compiler can be used file by file or folder by folder with thorough testing. Practice makes incredible cats. Thank you, Nadia!
Optimizing HTML5 Games: 10 Years of Learnings
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Optimizing HTML5 Games: 10 Years of Learnings
Top Content
Watch video: Optimizing HTML5 Games: 10 Years of Learnings
PlayCanvas is an open-source game engine used by game developers worldwide. Optimization is crucial for HTML5 games, focusing on load times and frame rate. Texture and mesh optimization can significantly reduce download sizes. GLTF and GLB formats offer smaller file sizes and faster parsing times. Compressing game resources and using efficient file formats can improve load times. Framerate optimization and resolution scaling are important for better performance. Managing draw calls and using batching techniques can optimize performance. Browser DevTools, such as Chrome and Firefox, are useful for debugging and profiling. Detecting device performance and optimizing based on specific devices can improve game performance. Apple is making progress with WebGPU implementation. HTML5 games can be shipped to the App Store using Cordova.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Performance Debugging
React Advanced 2023React Advanced 2023
148 min
React Performance Debugging
Workshop
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
High-performance Next.js
React Summit 2022React Summit 2022
50 min
High-performance Next.js
Workshop
Michele Riva
Michele Riva
Next.js is a compelling framework that makes many tasks effortless by providing many out-of-the-box solutions. But as soon as our app needs to scale, it is essential to maintain high performance without compromising maintenance and server costs. In this workshop, we will see how to analyze Next.js performances, resources usage, how to scale it, and how to make the right decisions while writing the application architecture.
Maximize App Performance by Optimizing Web Fonts
Vue.js London 2023Vue.js London 2023
49 min
Maximize App Performance by Optimizing Web Fonts
WorkshopFree
Lazar Nikolov
Lazar Nikolov
You've just landed on a web page and you try to click a certain element, but just before you do, an ad loads on top of it and you end up clicking that thing instead.
That…that’s a layout shift. Everyone, developers and users alike, know that layout shifts are bad. And the later they happen, the more disruptive they are to users. In this workshop we're going to look into how web fonts cause layout shifts and explore a few strategies of loading web fonts without causing big layout shifts.
Table of Contents:What’s CLS and how it’s calculated?How fonts can cause CLS?Font loading strategies for minimizing CLSRecap and conclusion