Search code examples
vue.jsiisvuejs3vue-routervite

Vue 3 / Vite not respecting base url when routing. Route refresh produces 404


Vue 3.2.13, Vite 3.2.5, vite-plugin-rewrite-all 1.0.1

Hosted on IIS

I've recently deployed an app I'm working on to IIS. I have to use the --base option with my build as my site is a Application in the website.

My base url would be https://example.com/myApplicaitons/myApp/vueRoute.

On the initial load my url is https://example.com/myApplicaitons/myApp/vueRoute but when navigating using a routing link I load my component successfully but the url is https://example.com/vueRoute instead of https://example.com/myApplicaitons/myApp/vueRoute and when I refresh it produces a 404.

I'm already using history mode for the router and I've even installed the rewrite-all node module as suggested in similar posts. I also have a web.config im public folder with the same configuration as https://v3.router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations.

I'll include my vite.config.js, router/index.ts and my script for building.

vite.config.js

// Plugins
import vue from "@vitejs/plugin-vue";
import pluginRewriteAll from "vite-plugin-rewrite-all";

// Utilities
import { defineConfig } from "vite";
import { fileURLToPath, URL } from "node:url";

// eslint-disable-next-line no-undef
const path = require("path");

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), pluginRewriteAll()],
  define: { "process.env": {} },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
      "~bootstrap": path.resolve(__dirname, "node_modules/bootstrap"),
    },
    extensions: [".js", ".json", ".jsx", ".mjs", ".ts", ".tsx", ".vue"],
  },
  server: {
    port: 3000,
  },
});

router/index.ts

// Composables
import { Component } from 'vue';
import ChildVue from '@/views/child/Child.vue';
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
    {
        path: '/',
        component: HomeVue,
    },
    {
        path: '/MyRoute',
        children: [
            {
                path: '/Child',
                name: 'Child',
                component: ChildVue,
            },
        ],
    },
] as Route[];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});

export default router;

export interface Route {
    path: string;
    name?: string;
    component: Component;
}

Build script "build-dev": "vite build --mode dev --base=/myApplicaitons/myApp/"

TIA


Solution

  • The problem is the use of process.env here:

    createWebHistory(process.env.BASE_URL)
    

    Vite exposes environment variables using import.meta.env. The above line should then be:

    createWebHistory(import.meta.env.BASE_URL)