Vuejs懒人加载路由器与webpack

时间:2018-01-10 14:06:36

标签: vue.js vuejs2 vue-component vue-router

遵循本指南:https://alligator.io/vuejs/lazy-loading-routes/

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

Vue.use(VueRouter)

const Other = r => require.ensure([], () => r(require('./components/Other.vue')))
const Home = { template: '<div><h2>Home Page</h2></div>'}

const routes = [
  { path: '/', component: Home },
  { path: '/other', component: Other }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

这将输出主js文件以及所述组件的另一个文件。相当无痛。

是否有可能以某种方式整理这个阵容。我试图在一个函数中包装该行但是这会发出一个警告: “./src/main.js中的警告 13:15-28关键依赖:依赖的请求是表达式“

以下是无法使用webpack构建的抽象...

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

Vue.use(VueRouter)

import About from './components/About.vue'
import Other from './components/Other.vue'

let lazyLoader = function( path ){
  return r => require.ensure([], () => r(require(path)))
}

const LazyAbstraction  = lazyLoader('./components/LazyLoadMePlease.vue')
const Home = { template: '<div><h2>Home Page</h2></div>'}
const Contact = { template: '<div><h2>Contact Page</h2></div>'}

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/lazy', component: LazyAbstraction },
  { path: '/contact', component: Contact },
  { path: '/other', component: Other }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

1 个答案:

答案 0 :(得分:0)

您不需要require.ensure

LazyLoading Vue

尝试此方法const Foo = () => import('./Foo.vue')

Webpack将为每个import()

解析另一个js文件