When the beta version of SvelteKit was announced, I immediately got excited and migrated my blog from Sapper to SvelteKit. Overall, the migration was very smooth and quick. The big reason why this went smooth is that the API is almost identical, and the docs and examples were helpful.
I just stumbled upon one problem with environment variables.
Sadly, it doesn't seem to have an easy fix, that's why I decided to write down a workaround (based on the answers given in that Github issue).
SvelteKit delegates its build step to Vite, which supports environment variables. To define environment variables, we must use the dotenv module.
For example, to define a base path, we need to add the variable to a .env.* file.
Note that all environment variables must be prefixed with VITE_, otherwise, the variables won't be exposed due to security reasons.
.env.development
VITE_PUBLIC_BASE_PATH=http://localhost:3000
When the environment variable is defined, we can now use the import.meta.env.VITE_PUBLIC_BASE_PATH variable in our code. These variables will be replaced by their corresponding values.
But as I mentioned before, there's one problem.
When the application is served you don't notice the issue, but with the build command, the following error is thrown when the component file (which uses an environment variable) includes a style tag.
The workaround to this problem is to extract the environment variables into a separate module.
Next, you can simply import the environment variable into your component from this module.