vue动态路由加载时出现Cannot find module xxx问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue动态路由加载时出现Cannot find module xxx问题

longzhoufeng   2023-02-02 我要评论

vue动态路由加载时报错Cannot find module xxx

vue由静态路由改为动态路由时,出现下面的错误

静态路由懒加载,当我们把在router里面,把它写死在ts里时,它加载的ok的,可是我们通过api接口拉取过来的数据时,发现是不报了上面的错

// 静态路由懒加载
export const loadView = (view: any) => {
  return () => import(`@/views/${view}.vue`)
}

错误原因是webpack打包逻辑,webpack4中动态import不支持变量方式,查看路由返回的信息,只是返回一个方法。

而静态路由的返回,这个才是正确的组件返回方式

但是我们是要改为动态路由,则必须把它修改为

这样动态路由加载就OK了

export const loadView = (view: any) => {
  return (resolve: any) => require([`@/views/${view}.vue`], resolve)
}

vue踩坑之旅

错误信息

Cannot find module '@/views/login/xxx'     at webpackEmptyContext (eval at ./src/router sync recursive (app.js:2562), <anonymous>:2:10)     at eval (asyncLoginRouter.ts?425a:20)

解决方法

①进入router中的index.js

component: () => import('@/views/login/index'),

改为

component: (resolve) => require(["@/views/login/index"], resolve),

②如果是动态路由则

export const loadView = (view) => { // 路由懒加载
return () => import(`@/views/${view}`)
}

改为

export const loadView = (view) => { // 路由懒加载
return (resolve) => require([`@/views/${view}`], resolve)
}

原因分析

webpack4中动态import不支持变量方式,

该修改对于生产环境无影响,只在开发环境有问题

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们