Home > Software engineering >  asynchronously load a group of modules
asynchronously load a group of modules

Time:06-24

In Vue.js (2.X) I can make a component load asynchronously - which means the code for that component will be stored in a separate bundle - by changing the corresponding route's definition from

// routes.js

import Messages from '@/views/messages'

export default [
  {
    path: '/messages',
    name: 'messages',
    component: Messages
  }
]  

to

// routes.js

export default [
  {
    path: '/messages',
    name: 'messages',
    component: () => import('@/views/messages')
  }
]  

Is there a way that I can bundle 2 (or more) route components together, such that the code for them is stored in the same bundle and loaded (asynchronously) simultaneously?

The reason I want to do this is because the components in this group are only accessible to a user with a certain role, so either all of them are accessible to a user, or none of them are.

CodePudding user response:

Documentation here.


@vue/cli

If you develop using @vue/cli, you're using webpack under the hood and you need to tell webpack how to group its chunks, using comments inside import():

const Foo = () =>
  import(/* webpackChunkName: "foo-bar" */ './Foo.vue')
const Bar = () =>
  import(/* webpackChunkName: "foo-bar" */ './Bar.vue')
const Baz = () =>
  import(/* webpackChunkName: "baz" */ './Baz.vue')

vite

In you develop using vite, you're using rollup under the hood and you need to tell rollup how to group chunks, in vite.config.js:

export default defineConfig({
  build: {
    rollupOptions: {
      // https://rollupjs.org/guide/en/#outputmanualchunks
      output: {
        manualChunks: {
          'foo-bar': [
            './src/Foo',
            './src/Bar',
          ],
          baz: [
             './src/Baz'
          ]
        },
    },
  },
})
  • Related