Search code examples
vue.jsvuejs2vue-routervitepnpm

How To Make Vue 2.7 On Vite Handle Second Sub Folder On Refresh Rather Than Throwing 404?


I have a Vue 2.7 project that is using Vite.

My vite.config.ts contains this:

resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },

And my index.ts file contains this:

const router = new VueRouter({
  mode: "history",
  base: import.meta.env.BASE_URL,
  routes: routes
});

Where my routes contain such route:

{
    path: "/x",
    name: "x",
    component: XView,
  },
  {
    path: "/x/y",
    name: "x2",
    component: XView,
  },

When I am in the application (started with pnpm run dev that calls "vite") I can navigate to "/x", and "/x/y". These routes work properly. Also, when I am at "/x", I can refresh the page and it shows up.

But when I am at "/x/y" and refresh the page, I see in the network tab that Vue tries to load:

http://localhost:5173/x/src/main.ts

Resulting in Not found 404. The page is blank.

It is wrong because the proper place of the main.ts file is:

http://localhost:5173/src/main.ts

How to make Vue 2.7 on Vite work properly when refreshing the second sub folder?


Solution

  • I've solved it by fixing paths in the index.html file by adding a slash before the path to indicate to load files from the root URL:

    Before:

    <script type="module" src="src/main.ts"></script>
    

    After:

    <script type="module" src="/src/main.ts"></script>
    

    The same goes for other paths in index.html.