require代替import解决vue项目首页加载时间过久的问题
vue的路由配置文件(routers.js),一般使用import引入的写法,当项目打包时路由里的所有component都会打包在一个js中,在项目刚进入首页的时候,就会加载所有的组件,所以导致首页加载较慢,而用require会将component分别打包成不同的js,按需加载,访问此路由时才会加载这个js,所以就避免进入首页时加载内容过多。
require: 运行时调用,理论上可以运用在代码的任何地方
import:编译时调用,必须放在文件开头
import写法:
import userCenter from '@/page/usercenter/index.vue'
export default [
{
path: '/userCenter',
name: 'user-center',
component: userCenter
},
{
path: '/news/detail',
name: 'news-detail',
component: () => import('@/page/news/detail.vue')
}
]
require写法:
export default [
{
path: '/userCenter',
name: 'user-center',
component: resolve => require(['@/page/userCenter/index.vue'], resolve)
},
{
path: '/news/detail',
name: 'news-detail',
component: () => resolve => require(['@/page/news/detail.vue'], resolve)
}
]