【问题标题】:Alternative for "component: () => import()" in VueJS routingVueJS 路由中“component: () => import()”的替代方案
【发布时间】:2019-10-14 07:02:51
【问题描述】:

我在网上下载了一个模板以更好地理解 VueJS 并创建了一个 Web 应用程序。但是我的路由有问题。我的路由器的 index.js 中有一个函数可以导入路径。由于一些 webpack 问题,导入语法似乎有问题。我尝试了很多不同的方法,但无法修复错误,所以我想为 import 语法找到解决方法

这是我的路由器 index.js 代码

import Vue from 'vue'
import VueAnalytics from 'vue-analytics'
import Router from 'vue-router'
import Meta from 'vue-meta'

// Routes
import paths from './paths'
// import views from './views'

function route (path, view, name) {
  return {
    name: name || view,
    path,
    component: () => import(
      `../views/${view}.vue`
    )
  }
}

Vue.use(Router)

// Create a new router
const router = new Router({
  mode: 'history',
  routes: paths.map(path => route(path.path, path.view, path.name)).concat([
    { path: '*', redirect: '/home' }
  ]),
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    if (to.hash) {
      return { selector: to.hash }
    }
    return { x: 0, y: 0 }
  }
})

Vue.use(Meta)

// Bootstrap Analytics
// Set in .env
// https://github.com/MatteoGabriele/vue-analytics
if (process.env.GOOGLE_ANALYTICS) {
  Vue.use(VueAnalytics, {
    id: process.env.GOOGLE_ANALYTICS,
    router,
    autoTracking: {
      page: process.env.NODE_ENV !== 'development'
    }
  })
}

export default router

当我尝试构建它时,我收到一条错误消息:

ERROR in ./src/router/index.js
Module build failed: SyntaxError: C:/djangoProjects/martin - Copy/martin/src/router/index.js: Unexpected token (15:21)

语法错误在线 (15:21),在 component: () => import( 行上的 route 函数中以及在 import 上。解决这个问题很痛苦,所以我想知道是否有不使用import 语法的解决方法?

【问题讨论】:

    标签: javascript vue.js vue-router


    【解决方案1】:

    如果我没记错的话,你需要一个可以处理动态导入的 babel 插件。

    查看: https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import

    1. 运行npm install @babel/plugin-syntax-dynamic-import
    2. 创建或打开.babelrc
    {
        "plugins": ["@babel/plugin-syntax-dynamic-import"]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-25
      • 2018-02-17
      • 1970-01-01
      • 2021-04-18
      • 2013-07-13
      • 2018-06-12
      • 2014-08-29
      相关资源
      最近更新 更多