vue实现按需加载(懒加载)
具体操作只需要两步:1.router文件中使用import Vue from 'vue'import Router from 'vue-router'Vue.use(Router)const routes = [{path:'/',component:resolve => require(['@/components/First'],resolve)},{path...
·
具体操作只需要两步:
1.router文件中使用
import
Vue
from
'vue'
import
Router
from
'vue-router'
Vue.
use(
Router)
const
routes = [
{
path:
'/',
component:resolve
=>
require([
'@/components/First'],
resolve)
},
{
path:
'/first',
component:resolve
=>
require([
'@/components/First'],
resolve)
},
{
path:
'/second',
component:
resolve
=>
require([
'@/components/Second'],
resolve)
}
]
//最后创建router 对路由进行管理,它是由构造函数 new vueRouter() 创建,接受routes 参数。
const
router =
new
VueRouter({
routes
})
export
default
router;
直接这样写不做其他处理webpack打包时会使用id作为chunkFileName
2.或者这样:
import
Vue
from
'vue'
import
VueRouter
from
'vue-router'
Vue.
use(
VueRouter)
export
default
new
VueRouter({
routes: [
{
path:
'/',
name:
'Navigator',
component: ()
=>
import(
/* webpackChunkName: "navigator" */
'./../components/a')
},
{
path:
'/tucao',
name:
'Tucao',//
webpackChunkName: "tucao"((值一样时会打包到通过文件中)
component: ()
=>
import(
/* webpackChunkName: "tucao" */
'./../components/b')
}
]
})
在webpack.base.conf.js文件中配置chunkFileName
output: {
path:
config.
build.
assetsRoot,
filename:
'[name].js',
chunkFilename:
'[name].js', //以文件名为最终打包的名称
publicPath:
process.
env.
NODE_ENV ===
'production'
?
config.
build.
assetsPublicPath
:
config.
dev.
assetsPublicPath
},
更多推荐
已为社区贡献1条内容
所有评论(0)