Léo Coco
Léo Coco

Reputation: 4282

Vue 2 - Import on demand

import Vue from 'vue'

import { 
         Button, 
         Select,
         Table,
         Form, 
        } from 'element-ui'


import App from './App.vue'

Vue.component(Button.name, Button)
Vue.component(Select.name, Select)

// Used by admin section of the website
Vue.component(Table.name, Table)
Vue.component(Form.name, Form)

const routes = [
    { path: '/', component: Home },
    { path: '/admin', meta: { requiresAuth: true }, component: Admin},
];

new Vue({
  el: '#app',
  render: h => h(App)
})

I am using the components Button and Select for everyone, but I'm using the Table and Form ones only for the admin page. The admin section is a Vue component that includes others components.

Here is the question. Since I want to optimize the size of the bundle build by Webpack, how could I import import Button and Select by default, but Table and Form just if you reach the admin section ?

I guess I would need to have more than one chunk in Webpack but I'm not sure how to do it.

Thank you

Upvotes: 0

Views: 1034

Answers (2)

Existe Deja
Existe Deja

Reputation: 1379

You're right, you'll need to separate your file into several ones. You should take a look at single files component.

This way you'll be able to manage your dependencies in a component level.

And if you feel more confortable with tolls tha auto-configure (almost) everything for you, vue-cli is the tool you need.

Upvotes: 1

Léo Coco
Léo Coco

Reputation: 4282

I just missed that in the Vue Router documentation

const Foo = resolve => {
  // require.ensure is Webpack's special syntax for a code-split point.
  require.ensure(['./Foo.vue'], () => {
    resolve(require('./Foo.vue'))
  })
}

Upvotes: 0

Related Questions