Svelte is a new, up-and-coming framework for building fast web applications. In contrast to React, it does a lot of the heavy lifting in a compile step instead of in the browser. It's very clever and comes with enormous advantages but can also have its pitfalls for developers used to the more popular frameworks. In case of the environment variables, one can't just import dotenv
wherever and assume it will work - a replace plugin of rollup (the bundler) has to be used instead. This tutorial uses yarn
for a package manager and would work the same with npm
.
Using dotenv and rollup's replace plugin to load environment variables
In order to be able to load environment variables like we're used to: process.env.<variable-name>
, we will use @rollup/plugin-replace
together with dotenv
.
The magic will happen in the rollup.config.js
file which tells rollup how to build our project. First, go ahead and install the required dependencies using yarn
or npm
. I'll assume yarn. Run yarn add --dev @rollup/plugin-replace dotenv
and create a .env
file (remember to git ignore it) in the main folder of your repo.
Now, in your rollup config, tell rollup to use the replace plugin, define which files it should include in the replacement procedure and which strings you want to replace:
.
.
.
plugins: [
replace({
include: ["src/**/*.ts", "src/**/*.svelte"],
preventAssignment: true,
values: {
"process.env.TESTVAR": "'replacedtestvar'"
}
}),
.
.
.
Note that the replacement happens at compile time which means that if you don't wrap the values of the provided dictionary in an additional quotation, javascript will be looking for a variable of that name instead of understanding that it was supposed to be a string. Thus, in order to use the familiar process.env.<variable-name>
we will make a simple transformation of our config loaded using dotenv.
First import dotenv at the top of your rollup.config.js
:
import { config } from 'dotenv';
Then proceed to transform the env. variables to suit the replace plugin:
const configToReplace = {};
for (const [key, v] of Object.entries(config().parsed)) {
configToReplace[`process.env.${key}`] = `'${v}'`;
}
And finally adjust the plugins option of the exported rollup config:
.
.
.
plugins: [
replace({
include: ["src/**/*.ts", "src/**/*.svelte"],
preventAssignment: true,
values: configToReplace,
}),
.
.
.
Make sure to adjust the include option of the plugin and then you can joyfully write process.env...
to access the properties you loaded from your .env file.
Top comments (1)
Thank you