Laravel & Vite: Setting Up Multiple Bundles


Fathom Banner

Currently Vite doesn't support multiple inputs, there fore you can not create different bundles with the same Vite config.

You will need multiple Vite configs if you want separate build files to use in different parts of your app. This can be accomplished by creating a secondary Vite config and adding a new script to your package.json.

New Vite Config

As you see in my package.json I chose to name my script vite.widget.config.js, but you can name it whatever you want. Here is my Vite secondary Vite config.

I'm adding a new hotFile and buildDirectory. The separate hot file allows you to run dev mode for both configs simultaneously.

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            hotFile: 'public/widget.hot',
            buildDirectory: 'widget',
            input: [
                'resources/css/widget.css',
                'resources/js/widget.js'
            ],
            refresh: true,
            valetTls: 'responserocket.test',
        }),
    ],
});
Secondary Vite config

Update your package.json

I've added a new dev and build script for my new config file, as well as a single command that I can use to build all my configs.

  "scripts": {
      "dev": "vite",
      "build": "vite build",
      
      "dev.widget": "vite --config vite.widget.config.js",
      "build.widget": "vite build --config vite.widget.config.js",
      
      "dev.all": "npm run dev && npm run dev.widget",
      "build.all": "npm run build && npm run build.widget"
  },
package.json script section

Update your Vite resource injection method

Instead of calling @vite() in your blade template you'll need to use the following method instead

{{Vite::useHotFile('widget.hot')
    ->useBuildDirectory('widget')
    ->withEntryPoints(['resources/js/app.js'])}}

You can see more here:  Laravel Asset Documentation

Thanks for stopping bye!