webpackvuejs2vue.jswebpack-2

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


Solution

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