【问题标题】:How to bundle Vite Vue Router 4 into same chunk如何将 Vite Vue Router 4 捆绑到同一个块中
【发布时间】:2021-09-11 07:15:05
【问题描述】:

使用 vue cli,您可以使用 web-pack 将 vue 路由块捆绑在一起

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') }
    ]
  }
]

我目前正在为一个项目使用 Vite。有没有办法将块(例如 Dashboard 和 Portal)捆绑在一起?

运行 nom run build 将为 Portal.js 和 Dashboard.js 生成单独的块文件

谢谢

【问题讨论】:

    标签: vue-router vuejs3 vite vue-router4


    【解决方案1】:

    为了能够动态加载视图,您必须按以下方式应用导入 () => import ('Module'),如果我们想要将其按组划分,则必须在 vite.config 中指定它。 [js,ts]我给你举个小例子

    // 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()]
    });
    

    如果您需要更多信息,可以查看 vue-router 文档:https://next.router.vuejs.org/guide/advanced/lazy-loading.html#grouping-components-in-the-same-chunk

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 1970-01-01
      • 2019-06-07
      • 2022-09-27
      • 2020-08-31
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      相关资源
      最近更新 更多