Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 87 ยท Performance, Security and Ecosystem

Build and Load Performance

Make a Vue app load fast. Learn what ends up in your bundle, how tree shaking and code splitting work, and how to lazy load routes and components with Vite.

The previous lessons were about how fast a Vue app runs after it has loaded. This lesson is about the step before that: how much code the browser must download, parse and execute before the first screen appears. On a fast laptop with a fiber connection you will hardly notice a 1 MB bundle. On a mid-range phone with a shaky mobile connection, the same bundle can mean several seconds of a blank page.

Build-time performance is mostly a matter of shipping less code up front. You do that in three ways: by keeping dependencies small, by letting the build tool remove code nobody calls (tree shaking), and by splitting the rest into chunks that load only when the user needs them (code splitting). As always, measure before you optimize: the performance basics lesson shows the habit, and this lesson gives you the tools for the loading side.

What actually ships

When you run a production build with Vite, your .vue files, your JavaScript and your dependencies are bundled into a few static files with hashed names, for example assets/index-3f9a1c2e.js. A typical Vue app bundle contains four kinds of code:

  • Vue itself. The runtime is the part that creates and updates the DOM. Because Vue is built from ES modules, features you never use (such as Transition or KeepAlive) can be dropped from the bundle.
  • Your own code. Components, composables and stores.
  • Third-party libraries. This is very often the biggest part. A charting library, a rich text editor or a date library can each be larger than Vue and your whole app put together.
  • Assets. Small images and fonts may be inlined, larger ones become separate files.

One detail is specific to Vue. In the live examples on this site, components are written as template strings, so the browser needs the full build of Vue, which includes the template compiler. In a real project with a build tool, single-file components are compiled to render functions ahead of time, so the app uses the smaller runtime-only build. This is one more reason to prefer SFCs and a build step for anything you deploy (see Ways to Use Vue).

flowchart LR
  A["main.js"] --> B["App.vue"]
  A --> V["vue runtime"]
  B --> C["HomeView.vue"]
  B --> D["ChartView.vue"]
  D --> L["big chart library"]
  A --> R["bundler"]
  R --> O["one large file<br/>or several chunks"]

Everything reachable through plain static imports from the entry file ends up in the initial download, including the big chart library behind a view the user may never open.

Measure the bundle

You cannot fix what you cannot see. Vite prints every output file with its raw and gzip size at the end of vite build. For a deeper look, a bundle visualizer draws a map in which each rectangle is a module and its area is its size. The following commands are read-only here (the site cannot run a build), but they work in any Vite project:

Terminal
npm run build
npx vite-bundle-visualizer

The visualizer opens a treemap. Look for three things: the biggest rectangles, libraries that appear twice in different versions, and large modules that sit in the initial chunk although only one screen needs them. Those are your candidates.

Compare sizes after gzip or Brotli compression, since that is what travels over the network (most hosts and CDNs compress text files automatically). JavaScript still has to be parsed and executed after it arrives, so the uncompressed size matters for CPU time on weak devices.

Below is a small interactive model of a bundle budget. The numbers are made up for illustration, but the habit is real: decide a limit for the initial JavaScript, and check each dependency against it before you add it.

A bundle budget

Untick the rich text editor and the chart library. The bar turns green, because the app fits the budget again. The next sections show how to keep a feature without paying for it up front.

Tree shaking

Tree shaking means that the bundler follows your import statements, finds exports that nothing uses, and leaves them out. It only works with ES modules, because their imports and exports are static and can be analyzed without running the code. A few habits make it effective:

JavaScript
// Good: one named import. The rest of the library can be dropped.
import { formatDate } from "date-helpers";

// Worse: the whole namespace object is kept alive.
import * as helpers from "date-helpers";

// Avoid for libraries that ship as one CommonJS file.
import _ from "lodash";          // pulls in everything
import debounce from "lodash-es/debounce"; // ES module, one function

When you evaluate a new dependency, look for these signs of a tree-shakeable package: an ES module build ("module" or "exports" in its package.json), "sideEffects": false, and an API made of many small functions rather than one big object. Icon libraries are a classic trap: import the icons you use by name, not the whole set.

Vue and Vite do their part too. Vue's own features are separate exports, so a build that never uses Teleport does not contain its code. In your app, keep module top levels free of side effects (code that runs just by being imported), since a bundler must keep any module whose import has an effect.

Code splitting with dynamic import

Tree shaking removes code nobody calls. Code splitting handles code somebody calls later. The tool is the dynamic import() expression, which returns a promise. When the bundler sees it, it puts the imported module and its private dependencies in a separate chunk file that is downloaded only when the call runs.

JavaScript
// Static import: part of the initial bundle.
import ChartView from "./views/ChartView.vue";

// Dynamic import: its own chunk, fetched on demand.
const loadChartView = () => import("./views/ChartView.vue");

Vue gives you two places to use this. The first is a single component, wrapped with defineAsyncComponent, which you met in Dynamic and Async Components. The second is the router: each route's component can be a function that returns a dynamic import, so every screen becomes its own chunk. This is called route-level lazy loading, and it is usually the best first step because the user can only look at one screen at a time.

JavaScript
// router.js (read-only: the site has no Vue Router package)
import { createRouter, createWebHistory } from "vue-router";
import HomeView from "./views/HomeView.vue"; // needed immediately

export default createRouter({
  history: createWebHistory(),
  routes: [
    { path: "/", component: HomeView },
    { path: "/reports", component: () => import("./views/ReportsView.vue") },
    { path: "/settings", component: () => import("./views/SettingsView.vue") }
  ]
});

The home screen is bundled with the app because it is shown first. Reports and Settings are fetched the first time someone navigates to them. Read more about the router in Vue Router Basics.

The demo below simulates this with a fake chunk loader that takes half a second. It counts how many "chunks" were fetched. Opening the same view twice fetches it only once, because a module is loaded one time and then reused.

Lazy components and fake chunks

Click Reports: you see the loading message for half a second, then the view. Go back to Home and open Reports again: it appears at once, and the list of fetched chunks still shows reports only once. In a real app the loading time depends on the network, and the browser also caches the chunk file.

Smarter splitting and prefetching

A few more tools help once the basics are done:

  • Preloading. Vite adds modulepreload hints for the chunks an entry needs, so the browser fetches them in parallel instead of discovering them one by one.
  • Prefetch on intent. You can start loading a route chunk when the user hovers a link or when the browser is idle, so the click feels instant. Calling the loader function early (loadChartView()) is enough, as the module is cached after the first call.
  • Manual chunks. With build.rollupOptions.output.manualChunks in vite.config.js you can place stable vendor code (Vue, the router) in its own file. It rarely changes, so returning visitors keep it in the browser cache while your own code changes with every release.
  • Hashed file names and long cache headers. Vite names files by content hash, so you can tell browsers to cache them for a year. A new release produces new names and old caches are never stale.
  • Compression. Serve Brotli or gzip. This often cuts JavaScript to a quarter of its size.

Splitting is not free. Too many tiny chunks means many requests, and a lazy view that the user opens right away just moves the delay from the start to the click. Split along natural boundaries: screens, modals, heavy widgets, admin-only areas. Keep the first screen, and anything almost every user touches, in the main bundle.

A practical checklist

  1. Run vite build and note the largest files.
  2. Open the visualizer and find the five biggest modules.
  3. Replace heavy libraries with lighter ones, or import only the parts you need.
  4. Lazy load routes and heavy components behind dynamic imports.
  5. Make sure images are sized and compressed, and fonts are subsetted.
  6. Check the result on a throttled network and a slow CPU in the browser's developer tools, not only on your own machine.
  7. Write the budget down (for example "initial JS under 150 kB gzip") and check it whenever you add a dependency.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does tree shaking do?

    Tree shaking follows static ES module imports and leaves out exports that are never used. Splitting into chunks is code splitting, and compression is a separate step.
  2. 2. Which line makes the bundler put a view into its own chunk?

    A dynamic import() creates a split point. A static import keeps the module in the importing chunk, and registering a component does not change where its code lives.
  3. 3. Why is route-level lazy loading a good first step?

    Each route is a natural boundary: code for screens the user has not visited yet does not need to be in the first download.
  4. 4. Why does a project with SFCs ship less code than a template-string app?

    A build tool compiles SFC templates to render functions, so the app can use the smaller runtime-only build of Vue without the compiler.

Summary

  • Initial load cost is download, parse and execute time; measure it with vite build output and a bundle visualizer.
  • Third-party libraries are usually the largest part of a bundle: pick light ones and import only what you use.
  • Tree shaking removes unused exports and needs ES modules and side-effect-free code.
  • Dynamic import() creates chunks that load on demand; use it for routes and heavy components.
  • Preload, hashed file names, cache headers and compression make the chunks cheap to fetch.
  • Set a bundle budget and check it whenever you add a dependency.

Next, in Security in Vue, you will see how to keep user-supplied content from turning your fast app into an attack surface.