【前端芝士樹】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'
  ]
}
相關文章
相關標籤/搜索