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

背景:参考Vue官方文档实现路由懒加载的时候遇到问题,具体文章 请戳此处
参考连接: Vue-loader官方网站

简介:Vue 路由懒加载

首先,能够将异步组件定义为返回一个 Promise 的工厂函数 (该函数返回的 Promise 应该 resolve 组件自己):css

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

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

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

结合这二者,这就是如何定义一个可以被 Webpack 自动代码分割的异步组件。vue

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

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

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:web

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

Changevue-router

{ "presets": ["env"] }

Tojson

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

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

修改webpack的配置文件sass

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'
  ]
}
相关文章
相关标签/搜索