0
0
VueHow-ToBeginner · 3 min read

How to Reduce Bundle Size in Vue for Faster Apps

To reduce bundle size in Vue, use dynamic imports for lazy loading components, enable tree shaking by importing only needed parts, and apply code splitting in your build setup. These techniques help load only necessary code, making your app faster and smaller.
📐

Syntax

Vue supports lazy loading components using dynamic imports. This syntax loads components only when needed, reducing initial bundle size.

Example syntax:

const MyComponent = () => import('./MyComponent.vue')

Here, import() is a function that returns a promise to load the component asynchronously.

javascript
const MyComponent = () => import('./MyComponent.vue')
💻

Example

This example shows how to lazy load a Vue component using dynamic import inside the router setup. The component loads only when the user visits its route.

javascript
import { createRouter, createWebHistory } from 'vue-router'

const Home = () => import('./components/Home.vue')
const About = () => import('./components/About.vue')

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
Output
When navigating to '/' or '/about', only the needed component is loaded, reducing initial bundle size.
⚠️

Common Pitfalls

1. Importing entire libraries: Importing full libraries instead of specific functions increases bundle size.

2. Not using lazy loading: Loading all components upfront makes the bundle large and slow.

3. Ignoring build optimizations: Not enabling tree shaking or code splitting in your bundler leads to bigger bundles.

javascript
/* Wrong: importing entire lodash library */
import _ from 'lodash'

/* Right: import only needed function */
import debounce from 'lodash/debounce'
📊

Quick Reference

  • Use dynamic imports to lazy load Vue components.
  • Import only needed parts of libraries to enable tree shaking.
  • Configure your bundler (like Vite or Webpack) for code splitting.
  • Remove unused code and dependencies.
  • Use tools like webpack-bundle-analyzer to inspect bundle size.

Key Takeaways

Use dynamic imports to lazy load components and reduce initial bundle size.
Import only specific functions from libraries to enable tree shaking.
Configure your bundler for code splitting to load code on demand.
Avoid importing unused code or entire libraries unnecessarily.
Analyze your bundle regularly to find and fix size issues.