0
0
Vueframework~5 mins

Bundle analysis and tree shaking in Vue

Choose your learning style9 modes available
Introduction

Bundle analysis helps you see what code is in your app's final files. Tree shaking removes unused code to make your app smaller and faster.

When your Vue app feels slow to load and you want to find big files.
Before deploying your app to make sure only needed code is included.
When adding new libraries and you want to check if they add too much size.
To understand which parts of your code or dependencies take most space.
Syntax
Vue
npm install --save-dev webpack-bundle-analyzer

// In vue.config.js
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  configureWebpack: {
    plugins: [new BundleAnalyzerPlugin()]
  }
};

This example uses webpack-bundle-analyzer with Vue CLI's webpack config.

Tree shaking happens automatically in production builds if your code uses ES modules.

Examples
Run the build command to generate the bundle and open the analysis report.
Vue
npm run build
// Then open the report in browser to see bundle sizes
Only the parts of Vue you import and use will be included in the final bundle thanks to tree shaking.
Vue
// Example of tree shaking
import { ref } from 'vue';

const count = ref(0);

// If you don't use other parts of Vue, they won't be included in the final bundle.
Sample Program

This config adds the bundle analyzer plugin to Vue's webpack setup. After building, it creates a static HTML report showing the size of each part of your app's bundle.

Vue
// vue.config.js
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  configureWebpack: {
    plugins: [new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      openAnalyzer: false,
      reportFilename: 'bundle-report.html'
    })]
  }
};

// Then run:
// npm run build

// After build, open 'bundle-report.html' in your browser to see the bundle analysis.
OutputSuccess
Important Notes

Tree shaking works best with ES module syntax (import/export).

Some libraries may not support tree shaking well if they use older module formats.

Bundle analysis helps you find large dependencies or unused code to optimize.

Summary

Bundle analysis shows what code is in your app's final files.

Tree shaking removes unused code automatically in production builds.

Use these tools to make your Vue app smaller and faster.