起因: 拉旧项目重跑发现运行报错,猜测是包更新导致部分写法不兼容。之后发现是原写法在webpack4中不兼容。所以这篇文章主要讲两部分:

1. 如何解决webpack4 动态编译import报错

2. imoort 和 require到底有什么区别?两者是否可以无缝替换?

 

一、解决报错
// 原写法
export const loadView = (view) => {
return () => import(`@/views/${view}`)
}

// webpack4 中动态import不支持以变量的方式,替换为下面的代码
export const loadView = (view) => {
return (resolve) => require([`@/views/${view}`], resolve)
}

export function getBackendRoutes(routes) {
  const res = []
  const keys = ['path', 'name', 'children', 'redirect', 'alwaysShow', 'meta', 'hidden']
  routes.forEach(item => {
    // alert('getBackendRoutes.routes item===' + JSON.stringify(item))
    const newItem = {}
    if (item.component) {
      if (item.component === 'layout/Layout') {
        newItem.component = Layout
      } else if (item.component === 'Layout') {
        newItem.component = Layout
      } else {
        const view = 'error-page/404'
        // newItem.component = () => import(`@/views/${view}`)
        // newItem.component = () => import(`@/views/error-page/404`)
        newItem.component = (resolve) => require([`@/views/${view}`], resolve)
      }
    }