EMZETT.
Login

Bundlers: Vite and webpack, bundling JavaScript for the browser

In short: A bundler combines many source files and packages into a few optimised files that the browser can load quickly.

In more detail: Modern web projects consist of hundreds of modules, TypeScript, JSX, CSS variants and libraries from npm. Browsers do not understand all of it directly and would make a separate request for every module. A bundler resolves the imports, transforms code and delivers optimised files.

In Depth

What a bundler does

  • Resolve dependencies: follows all import statements and builds a dependency graph.
  • Transform: convert TypeScript, JSX, newer language features and SCSS into browser-suitable JavaScript/CSS.
  • Bundle and split: combine modules and split them into sensible chunks so that only what a page needs is loaded (code splitting).
  • Optimise: minify, remove unused code (tree shaking), process images and fonts, add hashes to file names for long caching.
  • Development server with hot module replacement.

webpack

For a long time the standard, very flexible through loaders and plugins, but complex configuration and slow start in large projects. Many older projects and frameworks still use it.

Vite and newer tools

Vite uses, in development mode, the browser’s native ES modules: files are only transformed when needed (with esbuild), and startup is there in fractions of a second. For the production build Rollup is used (in newer versions Rolldown). Others: esbuild (very fast, written in Go), SWC and Turbopack/Rspack (in Rust) and Parcel (little configuration). Next.js and other frameworks bring their own bundler.

In practice

npm create vite@latest my-app -- --template react-ts
cd my-app && npm install
npm run dev        # development server
npm run build      # production files in dist/

The dist/ files can be served on any static hosting. Mind the bundle size (analysis tools such as rollup-plugin-visualizer); large libraries are worth finding alternatives to. With HTTP/2 and HTTP/3 bundling is less compelling than before, but optimisation and transformation remain necessary.

See also: Tree shaking, Node.js, Lighthouse and Core Web Vitals, TypeScript