Using Environment Variables with Svelte JS

Glory Katende
Webtips
Published in
2 min readAug 11, 2020

“Process is not defined”, the compiler just slapped you in the face again. You are tempted to hardcode your environment variables values in your code, then you realize just how much of a bad idea this is!

The default configuration of the sveltejs/template starter project doesn’t allow the use of environment variables out-of-the-box, The purpose of this article is to show you how you can change that.

Few tweaks in the default configuration will be all that is required, and rollup.js is where all the magic will happen.

Let’s start!

Make sure you already have a svelte project setup. If not, you can create one quickly:

degit sveltejs/template your-super-secret-project

Dependencies

First of all, you’ll want to install two dev dependencies. open your terminal and paste the following code:

npm i dotenv @rollup/plugin-replace --save-dev#Or If you are using yarnyarn add dotenv @rollup/plugin-replace -D

dotenv will load your environment variables from the .env file in the root directory of your project.

@rollup/plugin-replace will replace process.env.YOUR_ENV_VARS with their respective values.

Rollup Config

Next, you’ll want to open your rollup config file in the root directory of your project.

Import the packages you’ve just installed:

import { config } from 'dotenv';
import replace from '@rollup/plugin-replace';

Under Plugins, add the following:

plugins: [  
//...

replace({ FOO: 'bar',
process: JSON.stringify({
env: {
isProd: production,
...config().parsed
}
}),
}),

//...
]

To access .env values in your code, just use process.env.YOUR_ENV_VAR.

Done! Make sure to add .env to your .gitignore file.

Did you enjoy the article? be sure to share with someone who might find it useful.

Thanks for taking the time to read!

--

--