vue router history路由模式,配置多入口webpack-dev-server配置实践

1、问题由来,vue项目需要迁移history路由模式,但是涉及到多入口时,vue-router的总会把入口指向/下,导致其他入口无法访问,代码如下

// index入口
const router = new VueRouter({
  base: '/',
  routes,
  mode: 'history'
});

// index2入口
const router = new VueRouter({
  base: '/',
  routes,
  mode: 'history'
});
// webpack配置文件 
entry: {
   index: {
      import: './src/entries/index/index.ts'
    },
    index2: {
      import: './src/entries/index2/index.ts'
     }
  },

...
devServer:{
 
historyApiFallback: true
}

以上代码运行之后,就会出现无论如何都会默认重定向到/目录才能运行代码,不然就会404

2、分析原因:现象就是页面白屏,不是404,其实根本是location.pathname与我们vue的路由不匹配,需要同时修改vue-router的base和webpack的devServer配置才能实现本地开发模拟线上多入口的问题

 

 

以下配置也是为了多入口考虑 vue-router的路由和实际的location.pathname对应,才能正确显示页面

 3、配置兼容这种问题

  • 修改vue-router的base
// index入口
const router = new VueRouter({
  base: '/index/',
  routes,
  mode: 'history'
});

// index2入口
const router = new VueRouter({
  base: '/index2/',
  routes,
  mode: 'history'
});
  • 修改webpack的historyApiFallback配置重定向相关代码
// webpack配置设置
historyApiFallback: {
   verbose: true,
   rewrites: [
       {
         from: /(.*?)\//,
         to: ({ parsedUrl }) => {
            const entryName = parsedUrl.pathname.slice(0, -1);
            eturn  entryName + '.html';
          }
        }
      ]
  },
parsedUrl参数有哪些返回值
// 参数返回值 parsedUrl
parsedUrl Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: null,
  pathname: '/index2/',
  path: '/index2/',
  href: '/index2/'
}
Rewriting GET /index2/ to /index2.html
parsedUrl Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: null,
  pathname: '/index/',
  path: '/index/',
  href: '/index/'
}
Rewriting GET /index/ to /index.html

配置以上就可以正常本地访问多入口开发了

posted @ 2022-05-10 11:28  程序員劝退师  阅读(1402)  评论(0编辑  收藏  举报