require代替import解决vue项目首页加载时间过久的问题

    vue的路由配置文件(routers.js),一般使用import引入的写法,当项目打包时路由里的所有component都会打包在一个js中,在项目刚进入首页的时候,就会加载所有的组件,所以导致首页加载较慢,而用require会将component分别打包成不同的js,按需加载,访问此路由时才会加载这个js,所以就避免进入首页时加载内容过多。

    require: 运行时调用,理论上可以运用在代码的任何地方
    import:编译时调用,必须放在文件开头

    import写法:

    1. import userCenter from '@/page/usercenter/index.vue'
    2. export default [
    3. {
    4. path: '/userCenter',
    5. name: 'user-center',
    6. component: userCenter
    7. },
    8. {
    9. path: '/news/detail',
    10. name: 'news-detail',
    11. component: () => import('@/page/news/detail.vue')
    12. }
    13. ]

    require写法:

    1. export default [
    2. {
    3. path: '/userCenter',
    4. name: 'user-center',
    5. component: resolve => require(['@/page/userCenter/index.vue'], resolve)
    6. },
    7. {
    8. path: '/news/detail',
    9. name: 'news-detail',
    10. component: () => resolve => require(['@/page/news/detail.vue'], resolve)
    11. }
    12. ]