vue 路由配置及 webpack 分组打包

如下代码所示,最终打包发布后组件会被放在group-aa.jsgroup-bb.js两个文件中,这样可以很好的进行业务分离打包,用户访问时只需要下载对应的业务组件所在的文件。

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    { path: '/', name: 'Welcome', component: () => import(/* webpackChunkName: "group-aa" */'@/components/Welcome.vue') },
    { path: '/login', name: 'Login', component: () => import(/* webpackChunkName: "group-aa" */'@/components/Login.vue') },
    { path: '/home', name: 'Home', component: () => import(/* webpackChunkName: "group-bb" */'@/components/Home.vue'), meta: { isNeedLogin: true } },
    { path: '/bill', name: 'Bill', component: () => import(/* webpackChunkName: "group-bb" */'@/components/Bill.vue'), meta: { isNeedLogin: true } },
    { path: '/form', name: 'Form', component: () => import(/* webpackChunkName: "group-bb" */'@/components/Form.vue') },
    { path: '/404', name: '404', component: () => import(/* webpackChunkName: "group-aa" */'@/components/404.vue') },
    { path: '*', redirect: '/404' }
  ]
})

注意,要在 build\webpack.prod.conf.js 中配置输出因为有人命名。其中 [name] 即对应上面路由中配置的 webpackChunkName

output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[name].[chunkhash].js')
},

如果取不到chunkname可能需要引入babel-plugin-syntax-dynamic-import插件,并在.babelrc中配置。

"plugins": [
  "syntax-dynamic-import"
]
最后修改:2019 年 05 月 07 日 09 : 59 AM
如果觉得我的文章对你有用,请随意赞赏

发表评论