javascriptvue.jsvite

How do I access vite `base` config in app?


I recently used the base config API in my Vite app for deployment reasons:

// vite.config.js
export default defineConfig({
    plugins: [vue()],
    base: "/f2e/",
});

The file structure, in a nutshell, looks like this:

app
╞-public
|  └-foobar.jpg
└-src
   └-App.vue

As you see, there's an image in my app, using:

<!-- src.App.vue -->
<template>
    <img src="/foobar.jpg" />
</template>

Not surprisingly, the <img /> element is broken since the path is incorrect:

In /foobar.jpg

The server is configured with a public base URL of /f2e/ - did you mean to visit /f2e/foobar.jpg instead?

I know that we can use /f2e/foobar.jpg to fix the path, but, are there any APIs built in Vite that can access the base config? Just something like:

<!-- src.App.vue -->
<template>
    <img :src="locdBasePath() + '/foobar.jpg'" />
</template>

Because I don't think attaching the /f2e/ path in an app is a good practice, and refactoring all paths takes a lot of effect.

Have read Configuring Vite but nothing useful for my situation.


Solution

  • I found a more elegant way to do it.

    <!-- src.App.vue -->
    <template>
        <img src="/foobar.jpg" />
    </template>
    

    The point is the slash (/) in /foobar.jpg: The slash accesses my app's root directly, instead of the /f2e/foobar.jpg path that the app is assumed. And nothing's there at the root, so it broke.

    Removing the slash or adding a dot (to make it relative) can solve it.

    <!-- This works -->
    <template>
        <img src="foobar.jpg" />
    </template>
    
    <!-- This works, too -->
    <template>
        <img src="./foobar.jpg" />
    </template>
    

    A relative path is interesting.