记录Taro4+Vite 模板项目中,h5开启history路由模式,开发环境启动访问页面显示代码的问题及解决方案

38 阅读1分钟

问题

如图:在 taro+vite 模板项目中,在h5配置项下设置了路由模式为history模式

config/index.js image.png

  • 执行 npm run dev:h5 启动开发服务器,打开页面,好像一切正常

image.png

  • 当我刷新页面,WTF,发现 index 请求返回的内容有一丝不对劲

image.png

直接上解决方案

  1. 安装依赖
pnpm i connect-history-api-fallback -D
  1. 在 config/index.js 引入依赖
import history from 'connect-history-api-fallback'
  1. 在 compiler.vitePlugins 中添加以下配置项
 {
        name: 'configure-server',
        configureServer(server: any) {
          if (process.env.TARO_ENV === 'h5' && baseConfig?.h5?.router?.mode === 'browser') {
            server.middlewares.use(
              history({
                htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
              }))
          }
        }
      }
}

配置如下图: image.png

  • 最后重启开发服务器,就可以继续美美开发了 🍵🍵🍵