I recently learned a nice way to manage your .env files in your Svelte projects. If you're using Rollup as your bundling tool, which is likely to be the case, you can use the node module dotenv to automatically inject the content of a .env file into your web page.
Install dotenv via npm install dotenv
At the top of your rollup.config.js, import and load the environment variables:
import dotenv from "dotenv"
dotenv.config() // inject the content of the .env file into 'process.env'
Then, in the plugins section, if you're already using svelte-preprocess, modify the following:
And that's it. Now anywhere in your Svelte component and related Javascript (or Typescript) code you should be able to reference process.env.MY_ENV_VAR.
Use .env files with your Svelte project
November 11th 2020I recently learned a nice way to manage your
.env
files in your Svelte projects. If you're usingRollup
as your bundling tool, which is likely to be the case, you can use the node module dotenv to automatically inject the content of a.env
file into your web page.Install
dotenv
vianpm install dotenv
rollup.config.js
, import and load the environment variables:plugins
section, if you're already using svelte-preprocess, modify the following:And that's it. Now anywhere in your Svelte component and related Javascript (or Typescript) code you should be able to reference
process.env.MY_ENV_VAR
.