问题
I'm trying to improve the load time of my website, and towards that, I'm using the following settings in my vue.config.js
:
config.output.chunkFilename(`js/[name].[chunkhash:8].js`)
config.optimization
.runtimeChunk('single')
.splitChunks({
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name (module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`
}
}
}
})
Additionally, I also load all my routes dynamically:
router.js
const LandingPage = () => import(/* webpackChunkName: "view-landing-page" */ '@C/landing-page')
const HomePage = () => import(/* webpackChunkName: "view-home-page" */ '@C/home-page')
const Room = () => import(/* webpackChunkName: "view-room" */ '@C/room')
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'landingPage',
component: LandingPage
},
{
path: '/land',
name: 'landingPage',
component: LandingPage
},
{
path: '/home',
name: 'homePage',
component: HomePage
},
{
path: '/*',
name: 'roomPage',
component: Room
}
]
})
Each of these views also use lazy-loaded components. For example:
room.vue
export default {
name: 'room',
mixins: [SocketEventsMixin],
components: {
'video-element': () => import(/* webpackChunkName: "video-element" */ '@RC/media/video-element'),
'video-chat': () => import(/* webpackChunkName: "video-chat" */ '@RC/communications/video-chat'),
}
}
However, even with all this, I see the following in my index.html
:
...
<link href=/css/view-room.1ce954c7.css rel=prefetch>
<link href=/js/view-room.fe2de329.js rel=prefetch>
...
<link href=/css/video-element.8342e42f.css rel=prefetch>
<link href=/js/video-element.ab0e6cca.js rel=prefetch>
...
As a result, a whopping 4.5MB is downloaded on visiting the landing page, which does not require any of these assets.
How do I ensure that index.html
only contains the bare-minimum scripts/CSS, and have everything else be loaded dynamically? What causes an asset to be included in index.html
as opposed to being dynamically loaded? What am I doing wrong?
回答1:
Vue-CLI automatically sets webpackPrefetch: true
for all lazy-loaded components. I do not know how you can conditionally turn it on/off so in my projects I am turning it off completely:
// vue.config.js
chainWebpack: config =>
{
config.plugins.delete('prefetch'); // for async routes
config.plugins.delete('preload'); // for CSS
}
来源:https://stackoverflow.com/questions/62408282/vue-index-html-contains-link-tags-to-several-lazy-loaded-components