【前端芝士树】Vue - 路由懒加载 - 实践所遇问题摘记

发布时间:2019-05-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【前端芝士树】Vue - 路由懒加载 - 实践所遇问题摘记脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
背景:参考Vue官方文档实现路由懒加载的时候遇到问题,具体文章请戳此处
参考链接: Vue-loader官方网站

简介:Vue 路由懒加载

首先,可以将异步组件定义为返回一个 Promise 的工厂函数 (该函数返回的 Promise 应该 resolve 组件本身):

const Foo = () => PRomise.resolve({ /* 组件定义对象 */ })

第二,在 Webpack 2 中,我们可以使用动态 import语法来定义代码分块点 (split point):

import('./Foo.vue') // 返回 Promise
注意
如果您使用的是 Babel,你将需要添加 syntax-dynamic-import 插件,才能使 Babel 可以正确地解析语法。

结合这两者,这就是如何定义一个能够被 Webpack 自动代码分割的异步组件。

const Foo = () => import('./Foo.vue')

在路由配置中什么都不需要改变,只需要像往常一样使用 Foo:

const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo }
  ]
})

Vue-Cli3 中对路由懒加载的实现

import Vue From 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    },
    {
      path: '/organiser',
      name: 'organiser',
      component: () => import(/* webpackChunkName: "organiser" */ './views/Organiser.vue')
    }
  ]
})

问题一:Cannot read proPErty 'bindings' of null

Package.json:

"@babel/core": "^7.0.1",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.0.0",

Change

{ "presets": ["env"] } 

To

{ "presets": ["@babel/preset-env"] }

问题二:Error: vue-loader was used without the corresponding plugin

修改webpack的配置文件

const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
    devtool: "sourcemap",
    entry: './js/entry.js', // 入口文件
    output: {
        filename: 'bundle.js' // 打包出来的文件
    },
    plugins: [
        // make sure to include the plugin for the magic
        new VueLoaderPlugin()
    ],
    module : {
        ...
    }
}

问题三:Module parse failed: Unexpected character '#'

// webpack.config.js -> module.rules
{
  test: /.scss$/,
  use: [
    'vue-style-loader',
    {
      loader: 'css-loader',
      options: { modules: true }
    },
    'sass-loader'
  ]
}

脚本宝典总结

以上是脚本宝典为你收集整理的【前端芝士树】Vue - 路由懒加载 - 实践所遇问题摘记全部内容,希望文章能够帮你解决【前端芝士树】Vue - 路由懒加载 - 实践所遇问题摘记所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。