【问题标题】:Vuejs lazyloading router with webpack带有 webpack 的 Vuejs 延迟加载路由器
【发布时间】:2018-01-10 14:06:36
【问题描述】:

遵循本指南: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)
})

【问题讨论】:

  • 根据ES6,如果一个变量被多次重新赋值,推荐使用let
  • 嗯,把它改成 let from const 没什么区别:/
  • 你试过了吗? require.ensure([path], () => r(require(path)))

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


【解决方案1】:

你不需要require.ensure

试试这个方法const Foo = () =&gt; import('./Foo.vue')来自LazyLoading Vue

Webpack 会为每个import()解析另一个js文件

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 2020-01-06
    • 1970-01-01
    • 2015-03-28
    • 2019-01-13
    • 1970-01-01
    • 2020-05-31
    • 2022-07-25
    • 2017-05-17
    相关资源
    最近更新 更多