首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【前端芝士树】Vue - 路由懒加载 - 实践所遇问题摘记

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

作者头像
CloudCat
发布2022-05-06 15:28:02
2640
发布2022-05-06 15:28:02
举报

背景:参考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'
  ]
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介:Vue 路由懒加载
  • Vue-Cli3 中对路由懒加载的实现
  • 问题一:Cannot read property 'bindings' of null
  • 问题二:Error: vue-loader was used without the corresponding plugin
  • 问题三:Module parse failed: Unexpected character '#'
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档