Dynamic routing in Vue 3 + Vite development server causes 404 error on page reload
P粉811329034
P粉811329034 2023-10-27 08:49:33
0
2
842

In my project I use Vue 3.2.36 Vite 2.9.9 VueRouter 4.1.3

I run the development server using npm run dev.

My route definition:

routes: [
    {
      path: '/',
      component: Home,
    },
    {
      path: '/about',
      component: () => import('@/views/About.vue'),
    },
    {
      path: '/user-details/:login',
      name: 'userDetails',
      component: () => import('@/views/User.vue'),
    },
    {
      path: '/:pathMatch(.*)*',
      component: NotFound,
    }
  ],

When I navigate programmatically using router.push({name: 'userDetails', params: {login: 'john.smith'}}) the userDetails page /Component displays correctly.

But if my browser reloads the development server returns 404 and the NotFound component does not show up.

Chrome:


FF:


Working example: here

I've isolated the issue to Vite. Everything works fine using the Vue CLI.

My vite.config.js:

import loadVersion from 'vite-plugin-package-version';

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig(() => {
  return {
    server: {
      port: 8080,
    },
    plugins: [vue(), loadVersion()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    envDir: './src/configuration',
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/scss/_variables.scss";',
        },
      },
    },
  };
});

Checked my index.html:


Checked the vue-router historical mode documentation and in the warnings section it states that the router should default to index.html if the route is not found, and that it uses the Vue CLI to do this, But don't do this with Vite.

P粉811329034
P粉811329034

reply all(2)
P粉757556355

My web application is on Azure DevOps but on Linux For Linux web applications, you must add the next command to run the web application command on startup. This works for me.

pm2 serve /home/site/wwwroot --no-daemon --spa

You can see more in this article Azure webapp React application on linux

P粉011684326

Yes, it's aware of the bug in Vite.
The solution is to use plugins in Vite as described here

For me, this is a no-no. I'm going to switch to Vue CLI.
I don't want to deal with this kind of little monster.
I will visit Vite again in a few years.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!