I have a React App that uses Vite.
Everything is working as expected but I would like to see if we can customize the vite configuration further.
My goal is to make sure that my React app can be deployed from different subdirectories if needed and to make sure that we can serve the assets from different locations.
With my current set-up, my Vite config has the following:
vite.config.ts
build: {
// Tells the app where the assets will be served from.
assetsDir: "./apps/my-react-app",
sourcemap: false,
}
Everything is working as expected as long as I keep the production bundle files within "/apps/my-react-app" in production.
Is it possible for the vite.config.ts file to read a variable from, lets say the global window object?
This will enable me to declare something like window.assetsServedFrom = "./apps/another_directory_for_build_files" and then my vite config will be:
vite.config.ts
build: {
// Tells the app where the assets will be served from.
assetsDir: window.assetsServedFrom,
sourcemap: false,
}
I tried different ways to read a window variable but haven’t been successful.
It would be really great if this is possible.
Thank you
2
Answers
The vite config file is a static module which means that it not executed within the context of the browser and so, cannot access the
window
object. An alternative way to achieve what you want is to use environment variables.You need to create a
.env
file in your project root and declare your variable there. For exampleAnd then in your vite config file, you can access the variable by using
import.meta.env
. Here’s an example;Hope this helps!
You probably want to set the
base
path to./
With this setting your project will be built with relative references to your assets, instead of absolute paths.
For example, here is example
index.html
when built with defaultbase: '/'
(absolute paths from root)and here is the same
index.html
withbase: './'
(relative paths):With this change could deploy your built site to any public path and the project should load correctly (as long as you maintain the relative locations of the built assets to one another).