Other answers show how to do this in a hard-coded way. For most applications,
that's probably good enough. But if you want your build process to know nothing
about external parameters and get them through the environment, then read this.
There are several ways to provide base_url
: through the flag in your CI or
through environment variables: .env, github actions, whatever.
Flag
Run vite build --base=/my/public/path/
. The base URL should now be accessible
from your code as import.meta.env.BASE_URL
, so you can provide it to the
router of your choice as the base:
const App = () => {
return <Router base={import.meta.env.BASE_URL}>{...etc}</Router>;
};
Environment
For example, you can create an .env.production
file and load it before running
a build process. There are several ways to load .env
files: dotenvy-cli
,
godotenv
, dotenv-cli
- just to name a few.
# .env.production file
BASE_URL="/subdir/"
# If you want to expose variables to your app, use `VITE_` prefix.
# BASE_URL doesn't require a prefix although it will be exposed because we're
# gonna use it in the config.
VITE_API_URI="https://example.com/api"
VITE_DEFAULT_LANG="en"
// vite.config.ts
export default defineConfig({
// get exposed to your app as import.meta.env.BASE_URL
base: getBase(),
// rest of config
});
function getBase() {
if (!process.env["BASE_URL"]) {
throw new Error("BASE_URL environment variable is required");
}
return process.env["BASE_URL"];
}