Reputation: 397
Consider I have 4 components inside a page/component which user can use depends upon their selection (for ex:- toggle between Input comp || Image Comp || Video Comp || Vudio Comp ). I can lazily load them in two ways which is
1)
<template>
<component :is="compName">
</template>
data: () => ({compName: 'input'}),
components: {
input: () => import('/components/input'),
video: () => import('/components/video'),
audio: () => import('/components/audio'),
image: () => import('/components/image'),
}
2)
<template>
<component :is="loadComp">
</template>
data: () => ({compName: 'input'}),
computed: {
loadComp () {
const compName = this.compName
return () => import(`/components/${compName}`)
}
}
What difference will it make? Which is the correct way of dynamic import? Thanks in advance
Upvotes: 3
Views: 353
Reputation: 37983
Main difference is that in second case, Webpack does not know at build time what compName
value can be at runtime so it will automatically create separate bundle for every file in /components/
folder.
From docs
The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an
import()
call is included. For example,import('./locale/${language}.json')
will cause every.json
file in the./locale
directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file likeenglish.json
orgerman.json
will be available for consumption.
You can tune what should be included and what not with "magic comments" tho. For example following will bundle only .json
files from the folder
import(
/* webpackInclude: /\.json$/ */
`./locale/${language}`)
If that's what you want, both are valid and right ways to do dynamic imports. Second one with obvious advantage that you don't need to write imports one by one....
Second big difference is in the 1st case components are registered and you can use their names in the template as normal:
<template>
<input />
<video />
</template>
...whereas component resolved as in 2nd case is not registered and can be only used in <component :is="computed" />
Upvotes: 3