vue 动态加载时报错: Error: Cannot find module ‘@/views/xxx‘ at webpackEmptyContext

问题:vue在导出组件时在变量存在路径报错

vue-router.esm.js?8c4f:2208 Error: Cannot find module ‘@/views/production/index.vue‘
    at webpackEmptyContext (eval at ./src/router/modules sync recursive (app.js:35716), <anonymous>:2:10)
    at eval (content.js?fe3b:53)

vue 动态加载时报错: Error: Cannot find module ‘@/views/xxx‘ at webpackEmptyContext

思路

根据提示找到./src/router/modulescontent.js第53行,发现存在大量import ${type} 动态路径

contentRouter.push(
    {
      path: `/${type}/:id`,
      name: `details_${type}`,
      meta: {
        title: `${item.text}详情`,
        isDetail: true,
        contentType: type,
        keeyAlive: item.keepAlive ? item.keepAlive : false
      },
      component: () => import(`@/views/${type}/index.vue`)
    }
  );

解决:

查资料发现 原因:webpack 版本问题,webpack4中动态import不支持变量方式知道问题就不难解决了,这里使用require()来解决此问题

### 原写法:
component: () => import(`@/views/${type}/index.vue`)

### 修改后:
component: (resolve) => require([`@/views/${type}/index.vue`] ,resolve)

其它地方如果还有,也如此修改:

修改前
export const loadView = (view) => {
  return () => import(`@/views/${view}`)
}

修改后
export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

vue 动态加载时报错: Error: Cannot find module ‘@/views/xxx‘ at webpackEmptyContext

上一篇:设计与声明


下一篇:Python访问MySQL