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'
plugins
section, if you're already using svelte-preprocess, modify the following: plugins: [
svelte({
// ...
preprocess: sveltePreprocess({
// 👇 Add this attribute
replace: [["process.env.MY_ENV_VAR", process.env.MY_ENV_VAR]],
}),
}),
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
.