Everyone knows Vite is fast. But why?
I got some time, did some research and I want to document my learnings in this article. But first, let's take a look at how traditional build/dev tools work...
- You start your dev server (
- The bundler starts from an entry file, bundles your whole code and saves it in memory
- You save your changes
- Code gets re-bundled
- Bundled files are shipped to the browser
As you see, there's a lot of problems here already
- Cold starts: Your whole code will be bundled when you first start the dev server. Let's say you plan on fixing a bug in your login page, traditional bundle-based dev tools will crawl and build your entire application first. And yes, you guessed right! The larger your codebase, the longer the cold start.
- Dependencies vs source code: Dependencies are almost, always the largest part of your codebase. Some dev tools don't handle them separately given they almost do not change.
- Re-bundling on save: Even when these dependencies don't change, most traditional bundlers will also re-bundle them every time you save.
Vite is a dev-server based on native ES modules, it can also pair with Rollup to build code for production.
Vite took advantage of the fact that most browsers now understand ESM and it took out the bundling step. Instead of serving bundled files, we let the browser compose and follow it's own dependency graph through ESM.
These images from the vite docs, explain it perfectly...
Bundler follows an entry point, bundles all files and sends to the browser
All modules do not need to be bundled since the browser understands ESM
So why is Vite fast?
- ESM: A module system that browsers understand. No need for bundling.
- Esbuild & Rollup: Vite uses other faster build tools, e.g esbuild is written in Go, and rollup is faster because it's ESM-based.
- Dependencies vs source code: Vite prebundles dependencies with esbuild and serves it to the browser. It then caches these bundles since they almost never change.
A few other things to note
- Vite has native typescript support and you don't need to configure your tool to transpile typescript. It uses esbuild for this.
- ESM isn't fully supported by all browsers, so the code needs to be bundled for production. Vite uses rollup for this.
That'll be all for now. Until next time!