How to do multiple bundles with vite?

by darrion.kuhn , in category: Javascript , 2 months ago

How to do multiple bundles with vite?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , a month ago

@darrion.kuhn 

To create multiple bundles with Vite, you can use the splitChunks option in the Vite configuration file. Follow the steps below:

  1. Create a Vite configuration file named vite.config.js in the root of your project if you don't already have one.
  2. Configure splitChunks in the Vite configuration file to specify how the code should be split into multiple bundles. Here's an example of how you can create two bundles - one for your main application code and another for a vendor library:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['lodash']
        }
      }
    }
  }
})


In this example, the manualChunks option is used to create a separate bundle for the lodash library.

  1. Import the vendor library in your code as follows to ensure it gets bundled into a separate file:
1
2
3
4
// main.js
import _ from 'lodash'

console.log(_.add(1, 2))


  1. Run the Vite build command to bundle your code into multiple bundles:
1
vite build


This will generate two output files - one for your main application code and another for the vendor library code.


By using the splitChunks option in the Vite configuration file, you can create multiple bundles for your application code and vendor libraries. This can help improve the performance of your application by splitting the code into smaller, more manageable chunks.