vite icon indicating copy to clipboard operation
vite copied to clipboard

Allow to use different `base` for dev server and generated import paths

Open vincesp opened this issue 8 months ago • 6 comments

Description

As a developer using Vite in development mode, I want to configure the prefix used to generate the import paths separately from the prefix used by the dev server, so that I can run Vite in dev mode in a scenario with a reverse proxy that forwards traffic to different applications based on a URL prefix but removes that prefix when forwarding the request. Currently, I can only set base in the Vite config which will apply both to the prefix used by the dev server and to the import paths.

Suggested solution

Add an option server.base that can override the shared base option. With this, we could do:

import { defineConfig } from "vite";

export default defineConfig({
  base: "/foo/",
  server: {
    base: "/",
  },
});

Alternative

Alternatively, the overriding option could be added as build.base:

import { defineConfig } from "vite";

export default defineConfig({
  build: {
    base: "/foo/",
  },
});

Additional context

No response

Validations

vincesp avatar May 01 '25 12:05 vincesp

I'd recommend configuring the reverse proxy to keep the prefix if possible as that's much simplier. But if that's not an option, you can use a plugin like this: https://github.com/vitejs/vite/issues/19219#issuecomment-2601274229

sapphi-red avatar May 01 '25 12:05 sapphi-red

I'm not sure if I get what you are suggesting with build.base. But if you want to generate the base depending on whether it's a build or dev, you can use the conditional config feature in that case.

sapphi-red avatar May 01 '25 12:05 sapphi-red

The imports in the generated code always should have the prefix, both in dev as well as in prod. However, the dev server should not mount the root of the project under the prefix, but rather under '/'. This is for a setup where multiple sub products run in different containers, and there is a reverse proxy in the front that distinguished by the prefix to which container to forward each request. However, the reverse proxy will strip the prefix.

The Foo app could run on http://localhost:4321/

The reverse proxy on http://localhost:80/

A request to http://localhost:80/foo/main.js would be forwarded to http://localhost:4321/main.js.

So I need the Vite dev server to generate import URLs in the form of /foo/main.js but still serve the application at /.

vincesp avatar May 01 '25 17:05 vincesp

Then, I think the plugin I linked in https://github.com/vitejs/vite/issues/19980#issuecomment-2844750820 would work.

sapphi-red avatar May 02 '25 02:05 sapphi-red

@sapphi-red is there already an NPM package for that which we can import?

vincesp avatar May 02 '25 08:05 vincesp

I'm not aware of any existing package.

sapphi-red avatar May 02 '25 09:05 sapphi-red