Today I Learned - Rocky Kev

TIL how build tools work

POSTED ON:

TAGS:

I live and breathe Javascript. I live with a lot of domain knowledge. And when a new coder asks why their Javascript isn't working, I frequently have to light some torches, sing a chant and do a magic rain dance and then it works.

How does it work?

When you are building a project, it runs through 4 steps.

Step 1 - Compiling:

React, ESM modules, JSX, async/await, TypeScript, etc. But this code needs to be converted into vanilla JavaScript for the browser.

This is done by:

  1. Parsing the code into AST, or Abstract Syntax Tree
  2. Transform this AST into a representation that is supported by the target language
  3. Generate new code from this new AST representation

Step 2 - Minifying

The minifying step replaces function and component names with single characters to ship fewer kilobytes to the browser, improving performance for the end user.

Step 3 - Bundling

That allows us to use the file on it's own.

Despite [slug].tsx being only 56 lines long, it relies on many dependencies and components, which in turn relies on more dependencies and components. All of those modules need to be loaded for [slug].tsx to work properly.

Using dependency cruiser

Step 4 - Code-splitting

Code-splitting helps "lazy load" things currently needed by the user by loading only what is needed and avoiding code that may never be used. With React, you can experience up to 30% reduction in main bundle size when using code splitting.

Without code-splitting, a single, bundled JS file would be shipped to the client the first time a user touched the site, whether or not the entirety of that JavaScript was needed. With code-splitting, a performance optimization step, JavaScript is chunked by entry point (e.g. by page or by UI component) or by dynamic imports (so only a small portion of the JavaScript has to be shipped at any one time).

In other words, you have a global JS file that manages core features. Then separate JS for each individual page that has custom code.

via You Don't Need a Build Step


Related TILs

Tagged:

TIL how build tools work

There's 4 steps. Compiling -> Minifying -> Bundling -> Code-splitting

TIL of a nice ELI5 of code splitting

Code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel

TIL using code-splitting to improve your First Contentful Paint (FCP) score

Code splitting is a technique where you send only the necessary modules to the user in the beginning.