TIL how build tools work
POSTED ON:
TAGS: webpack ast buildtools minifying compiling bundling
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:
- Parsing the code into AST, or Abstract Syntax Tree
- Transform this AST into a representation that is supported by the target language
- 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: webpack