Vue.js dynamic component with webpack

2019-08-03 06:01发布

I am pretty lost with this problem:

In vue.js i want to dynamically load a component which might not be known beforehand. This is due to the wanted modularity of the planned application: a basic vue js application should be expanded by modular code e.g. dependend on some parameters coming from the database.

So, lets say the application directory looks like this one:

.
├── src //the main application
|    ├── components
|    │   ├── App.vue
|    └── index.js    
└── modules
  ├── Module1
  │   └── ExampleComponent.vue
  ├── Module2
      └── ...

The main idea is that App.vue loads e.g. a menu configuration via AJAX and displays it as async component.

// App.vue
<template>
    <div class="container">
        <async-component v-bind:is="component"></async-component>
    </div>
</template>
// [...]
axios.get("/getComponent")
   .then((response) => (
       this.component = window.Vue.component('component', (resolve) => {
           import(response.data["component"]).then(loadedComponent => {
               resolve(loadedComponent.default);
           });
       });
   )
 // [...]

This (here of course shortened) code more or less works but only if the component gets a fixed import. In every other case Webpack seems to ignore all the other present vue files. I already tried (among others) to disable the dead code removal by:

// [... webpack.config ...]
optimization: {
    sideEffects: false,
    minimizer: [
        new UglifyJsPlugin([
            uglifyOptions: {
                compress: {
                    unused: false,
                    dead_code: false
                }
            }
        ])
    ]
}

So here I am out of ideas how to achieve above setup. Thank you for your help!

0条回答
登录 后发表回答