Problem : In my vue-cli 4
app, I'd like to have build:
script, which generates production bundle, with specific .vue-components
not being included in some cases. In other cases they should be included. Also, these components are stored in app itself - not in external library.
I've tried : to import .vue-components
dynamically - let's say I have an array:
const customPreset = ['WidgetFirst', 'WidgetSecond', ...]
And empty object:
const widgets = {}
So I've tried to make something like this:
customPreset.forEach(v => { Object.assign(widgets, { [v]: () => import('./' + v + '.vue') }) })
export default widgets
Changing customPreset
to some other array would allow to import another set of components...
But that doesn't work, because import()
cannot operate with expressions.
So, what could be done to include various .vue-components
into production bundle in various cases? Maybe it could be achieved through tweaking vue.config.js
?
What you are looking for is lazy loaded components
. In Vue they are available at multiple points.
This is how to define an async component that will be automatically code-split by webpack:
const Foo = () => import('./Foo.vue')
You can also group components in the same chunk :
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')
Vue.component(
'async-webpack-example',
// The `import` function returns a Promise.
() => import('./my-async-component')
)
It even support loading state, straight from the box:
const AsyncComponent = () => ({
// The component to load (should be a Promise)
component: import('./MyComponent.vue'),
// A component to use while the async component is loading
loading: LoadingComponent,
// A component to use if the load fails
error: ErrorComponent,
// Delay before showing the loading component. Default: 200ms.
delay: 200,
// The error component will be displayed if a timeout is
// provided and exceeded. Default: Infinity.
timeout: 3000
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.