Today I've spent a quite long amount of time trying to figure out how to just serve a Vue3 + Vite page inside a sub-folder, so i decided to make a very quick post to help any people in the same situation.
So the URL was like https://example.com/my-page/
, and to make this happens, you need two changes
The first one is on vite.config.ts
or .js
, and add the parameter base: ''
, when using ''
will work with any sub-folder, since the index.html
assets URLs will start with ./
and use the relative path
export default defineConfig({
...,
base: '', // or the path instead if you want '/my-page/'
});
The second change, is inside your vue router , in my case src/router/index.ts
and add the parameter base in createWebHistory(base?: string)
const router = createRouter({
history: createWebHistory('/my-page/'),
routes: [...],
...
});
You could experiment with location.pathname
to make it agnostic of the folder name, but on my testing, it fail after navigating to another route
Alternatively, you could modify your index.html
instead of the router and just add the base tag like this <base href="https://example.com/my-page/">
Note that if you go to another route, ex: https://example.com/my-page/my-route
and refresh the page, it might show you the root page of https://example.com/
, this is something you will need to fix via your web server config such nginx, and doing that you might not need to do all these changes mentioned above, i recommend this setup just for showing a work in progress project, or one page landing, etc
I hope this was helpful.
References:
Top comments (0)