𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗕𝘂𝗻𝗱𝗹𝗶𝗻𝗴 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱

You write React or Angular apps using many files. You have components, services, and libraries. This organization helps you.

The browser does not care about your folders. If you load 200 files, the browser makes 200 network requests. This makes your app slow.

Bundlers solve this problem. A bundler takes your code, imports, and modules. It combines them into one or a few small files. This makes loading efficient.

Modern bundlers do more than combine files:

• Minification: It removes extra spaces and comments. It shortens variable names to make files smaller. • Tree shaking: It removes code you never use. It strips out unused functions from libraries. • Code splitting: It breaks code into small chunks. The browser only loads what the user needs right now.

Smaller files lead to faster apps.

Two main tools exist: Webpack and Vite.

Webpack bundles your whole app before serving it. This works well for large legacy projects. It is flexible but can feel slow in big projects.

Vite is the modern choice. During development, it serves files directly. It only updates the file you change. This makes updates instant. For production, Vite uses Rollup to create fast bundles.

Comparison:

Webpack:

  • Dev speed: Slower
  • Config: Complex
  • Best for: Large legacy projects

Vite:

  • Dev speed: Fast
  • Config: Simple
  • Best for: New modern projects

Use Vite for new projects.

Every bundler follows three steps:

  1. Build a dependency graph: It maps how every file connects to others.
  2. Transform code: It converts TypeScript or JSX into plain JavaScript.
  3. Output the bundle: It combines and minifies everything into a folder for deployment.

Keep your bundle lean with these steps:

• Lazy loading: Load components only when users navigate to them. • Partial imports: Do not import an entire library. Import only the specific function you need. • Analyze: Use tools to see what takes up space in your bundle. • Production builds: Always deploy production builds. Development builds are too large.

Bundling makes your app perform better by giving the browser fewer, smaller files.

Source: https://dev.to/kavya1205/javascript-bundling-explained-from-zero-to-optimised-f7p