vue 路由懒加载中给 Webpack Chunks 命名的方法

网络编程 2021-07-04 15:02www.168986.cn编程入门
这篇文章主要介绍了在 vue 路由懒加载中给 Webpack Chunks 命名的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

最早的路由定义方式

import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '../views/Home.vue'
import About from '../views/About.vue'
import Login from '../views/Login.vue'

Vue.use(VueRouter)

const routes = [
 { path: '/', name: 'Home', ponent: Home },
 { path: '/about', name: 'About', ponent: About },
 { path: '/login', name: 'Login', ponent: Login }
]

const router = new VueRouter({
 routes
})

export default router

进化版路由组件懒加载以及定义 chunk name

...
const routes = [
 {
  path: '/',
  name: 'Home',
  ponent: () => import(/ webpackChunkName: "Home" / '../views/Home.vue')
 },
 {
  path: '/about',
  name: 'About',
  ponent: () => import(/ webpackChunkName: "About" / '../views/About.vue')
 },
 {
  path: '/login',
  name: 'Login',
  ponent: () => import(/ webpackChunkName: "Login" / '../views/Login.vue')
 }
]
...

这样写起来是完全没有问题的,路由很多的情况下,这里的代码量就会增加,我们能不能把「路径」与「组件」绑定的操作放大循环里面去做呢

const routeOptions = [
 { path: '/', name: 'Home' },
 { path: '/about', name: 'About' },
 { path: '/login', name: 'Login' }
]
const routes = routeOptions.map(route => {
	return {
		...route,
		ponent: () => import(`@/views/${route.name}.vue`)
	}
})
const router = new VueRouter({
 routes
})

这样就优雅了不少,我们的 chunk name 还没有加上去,这个时候就要用到 webpack 2.6.0 以上的占位符[ index ]和[ request ]

const routeOptions = [
 { path: '/', name: 'Home' },
 { path: '/about', name: 'About' },
 { path: '/login', name: 'Login' }
]

const routes = routeOptions.map(route => {
 return {
  ...route,
  ponent: () => import(/ webpackChunkName: "[request]" / `../views/${route.name}.vue`)
 }
})

const router = new VueRouter({
 routes
})

build 一下就能看到想要的 chunk 了

到此这篇关于在 vue 路由懒加载中给 Webpack Chunks 命名的文章就介绍到这了,更多相关vue 路由懒加载内容请搜索狼蚁SEO以前的文章或继续浏览狼蚁网站SEO优化的相关文章希望大家以后多多支持狼蚁SEO!

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by