Vite: How to create separate bundles for large libraries

Photo by Davide Vattuone on Unsplash

Vite rolls up all your code into a single bundle. Sometimes it's better to build large libraries as separate bundles. You also might want to bundle rarely used libraries separately so you can lazy load the import. This is how you do it.

Vite config to create separate bundles

In your vite.config.ts file add the following:

export default defineConfig(() => {
  return {
    build: {
      rollupOptions: {
        output: {
          manualChunks: (id) => {
            if (id.includes('node_modules')) {
              if (id.includes('large-library')) {
                return 'vendor_large_library'
              } else if (id.includes('lodash')) {
                return 'vendor_lodash'
              return 'vendor' // all other package goes here
            }
          },
        },
      },
    },
    // all your other config
    //...

    // The analyse plugin is also useful if your checking bundle files
    plugins: [ analyze({ summaryOnly: true })],
  }
})

Hey! Are you a developer?

🚀 Set Up Your Dev Environment in Minutes, Not Hours!

Tired of spending hours setting up a new development machine? I used to be, too—until I automated the entire process!

Now, I just run a single script, grab a coffee, and let my setup take care of itself.

Save 30+ hours configuring a new Mac or Windows (WSL) development environment.
Ensure consistency across all your machines.
Eliminate tedious setup and get coding faster!
Get Instant Access →