skip to Main Content

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.

2

Answers


  1. Usually base is meant for serving project that is (and must) have its public root in some subdirectory on the server (remember the old site.com/~myusername thing, it is something alike).

    What you need is, I believe, is to redefine a project root.

    Another option would be to allow for serving foobar.jpg from other folders. For that you will need to add the folder containing it into server.fs.allow list:

    // vite.config.js
    import path from 'path'
    import { defineConfig, searchForWorkspaceRoot } from 'vite'
    
    const dir_root = searchForWorkspaceRoot(process.cwd())
    const projpth = (suf) => path.join(dir_root, suf)
    
    export default defineConfig({
        // ...
        server: {
            fs: {
                allow: [
                    // (!) unwrapped searchForWorkspaceRoot is not safe : exposes project root dir
                    // searchForWorkspaceRoot(process.cwd()),
    
                    // custom rules -- this is safe
                    projpth('CHANGELOG.md'),
                    projpth('assets')
                ],
            },
        },
    })
    
    Login or Signup to reply.
  2. From the docs for Public Base Path, I would have expected it to just work

    asset references in your .html files are all automatically adjusted to respect this option during build.

    However, if it is not working you can always prepend the injected import.meta.env.BASE_URL

    <img :src="`${import.meta.env.BASE_URL}/foobar.jpg`" />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search