Base url with multi page apps using vite

Viewed 2093

For my multi page app i cannot have html assets imports pointing to the root as i need to upload my project inside a sub-folder.

Using -

module.exports = defineConfig({
  base: "./",
});

resolves this issue for root pages but cause a wrong import for nested pages.

Example

 - assets
 - index.html
 - nested
   - nested.html

Imports for index.html will point to ./assets which is correct.

Imports for nested.html will also point to ./assets which is incorrect. It needs to point to ../assets instead.

1 Answers

You can set an alias to point to the assets folder :

alias: {
    "@": resolve(__dirname, './assets'),
 },

Based on your tree sample, with this following example of multipage vite.config.js, you can import assets from components with: import logo from '@/logo.png' (assuming there is a logo.png file in folder assets)

import vue from "@vitejs/plugin-vue";
import { join, parse, resolve } from "path";

export default {
  base: '',
  root: './',
  plugins: [vue()],
  alias: {
    "@": resolve(__dirname, './assets'), // will resolve to `/assets/`
  },
  build: {
    rollupOptions: {
      input: entryPoints(
        "index.html",
        "nested/nested.html",
        "foo/index.html",
        "foo/bar/index.html",
      ),
    },
  },
};

function entryPoints(...paths) {
  const entries = paths.map(parse).map(entry => {
    const { dir, base, name, ext } = entry;
    const key = join(dir, name);
    const path = resolve(__dirname, dir, base);
    return [key, path];
  });
  
  const config = Object.fromEntries(entries);
  return config;
}

Example code of the nested FooBar component :

<template>
  <img alt="Vue logo" :src="logo" />
  <Nav/>
  <h1>Foo Bar</h1>
</template>

<script setup>
  import Nav from "~/components/Nav.vue";
  import logo from '@/logo.png'

  import "@/style/style.scss"
</script>
Related