'How to bundle Vite Vue Router 4 into same chunk

using vue cli, you can bundle vue route chunk together using web-pack

const routes: Array<RouteRecordRaw> = [
  { path: '/', name: 'Home', component: Home },
  {
    path: '/login',
    name: 'Login',
    meta: { alreadyAuth: true },
    component: () => import(/* webpackChunkName: "login" */ '../views/public/Login.vue')
  },
  { path: '/splash', name: 'Splah', component: Splash },
  {
    path: '/portal',
    name: 'Portal',
    meta: { requireAuth: true },
    component: () => import(/* webpackChunkName: "portal" */ '../layouts/Dashboard.vue'),
    children: [
      { path: '', component: () => import(/* webpackChunkName: "portal" */ '../views/portal/Portal.vue') }
    ]
  }
]

I'm current using Vite for a project. Is there a way to bundle the chunk for example Dashboard and Portal together?

running nom run build will generate individual chunk file for Portal.js and Dashboard.js

Thanks



Solution 1:[1]

There has a vite plugin which can help. vite-plugin-webpackchunkname

Solution 2:[2]

To be able to load the views dynamically you must apply the import as follows () => import ('Module') and if what we want is to divide it by groups you have to specify it in the vite.config. [Js, ts] I leave you a little example

// routes.ts
const UserDetails = () => import('./UserDetails.vue')
const UserProfileEdit = () => import('./UserProfileEdit.vue')

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

const routes: Array<RouteRecordRaw> = [
  {
    path: '/user-details',
    component: UserDetails
  },
  {
    path: '/user-profile-edit',
    component: UserProfileEdit
  },
  {
    path: '/dashboard',
    component: Dashboard,
  },
]

// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')

export default defineConfig({
  build: {
    rollupOptions: {
      // https://rollupjs.org/guide/en/#outputmanualchunks
      output: {
        manualChunks: {
          'user': [
            './src/UserDetails',
            './src/UserProfileEdit',
          ],
          'dashboard': [
            './src/Dashboard',
          ],
        },
    },
  },
  plugins: [vue()]
});

If you need more information you can check the vue-router documentation: https://next.router.vuejs.org/guide/advanced/lazy-loading.html#grouping-components-in-the-same-chunk

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 liaofeiy
Solution 2