【前端芝士树】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'
  ]
}

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12759542.html