So I’m new to Vite and I use it for my svelte app
I really don’t understand this part of documentation
During production, these env variables are statically replaced. It is therefore necessary to always reference them using the full static string. For example, dynamic key access like import.meta.env[key] will not work.
I should mention that english is not my first language, and when I try the app on production it showed the env as the baseurl/undefined,
How am I supposed to get the env on production/after the application is build ?
I am currently using
import.meta.env.VITE_API_URL
to access the env in development,
This is my .env
VITE_BASE_URL="secret"
VITE_API_URL="secret/api"
I am using cloud run for my production and set the env in the cloud run dashboard. I also use this dockerfile for the production.
FROM node:16-alpine as build
WORKDIR /app
# copy files and install dependencies
COPY package.json .
COPY package-lock.json .
RUN npm install
COPY . .
RUN npm run run-build
COPY .env.production /app/dist/.env
FROM nginx:1.19
COPY ./nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=build /app/dist /usr/share/nginx/html
2
Answers
vite means that it won’t be able to understand if you dynamically access env
your syntax is valid and it should work
this is invalid syntax:
and you don’t need to do anything with the file
.env.production
both it will be used in production mode automaticallyThe issue
The replacement happens in the step
RUN npm run run-build
Running this step after the build
COPY .env.production /app/dist/.env
does nothing, this .env file is ignored.
A solution
Add a step before the build step to configure environment variables.