欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-04 17:03:52
最早的路由定义方式import vue from 'vue'import vuerouter from 'vue-router'import home from '../views/home.vue'...

最早的路由定义方式

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', component: home },
 { path: '/about', name: 'about', component: about },
 { path: '/login', name: 'login', component: login }
]

const router = new vuerouter({
 routes
})

export default router

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

...
const routes = [
 {
  path: '/',
  name: 'home',
  component: () => import(/* webpackchunkname: "home" */ '../views/home.vue')
 },
 {
  path: '/about',
  name: 'about',
  component: () => import(/* webpackchunkname: "about" */ '../views/about.vue')
 },
 {
  path: '/login',
  name: 'login',
  component: () => 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,
		component: () => 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,
  component: () => import(/* webpackchunkname: "[request]" */ `../views/${route.name}.vue`)
 }
})

const router = new vuerouter({
 routes
})

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

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

到此这篇关于在 vue 路由懒加载中给 webpack chunks 命名的文章就介绍到这了,更多相关vue 路由懒加载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!