DEV Community

Cover image for Adding Environment Variables to Svelte + TypScript Project
jancassio
jancassio

Posted on

Adding Environment Variables to Svelte + TypScript Project

I'm doing projects using Svelte with TypeScript for a few weeks. And I got myself in a simple issue that made me to spend a long time to figure out how to fix properly.

If you are looking for adding environment variables at your Svelte Typescript project. There are few steps to do that without break anything in your project.

In order to archive this, follow the steps below:

  1. Install @rollup/plugin-replace
  2. Also, install dotenv or dotenv-safe as your prefer.
  3. Create a global.d.ts file in the root of src folder and add the following script there:
// at global.d.ts
export {}

declare global {
  var __MY_ENV_VARIABLE__: string
  var __ANOTHER_ENV_VAR__: string
}
  1. Update rollup.config.js, adding replace plugin
// import it first
import replace from "@rollup/plugin-replace";

// then, add replace function before svelte plugin

...
plugins: [
  replace({
    globalThis: JSON.stringify({
      __MY_ENV_VARIABLE__: "my env variable value",
      __ANOTHER_ENV_VAR__: "another env var value",
    }),
  }),
  svelte({
...

Finally, you can access those variables using globalThis from TypeScript:

const MY_ENV_VARIABLE = globalThis.__MY_ENV_VARIABLE__;
const ANOTHER_ENV_VAR = globalThis.__ANOTHER_ENV_VAR__;

When Rollup built the bundle, the Replace Plugin will replace globalThis.__MY_ENV_VARIABLE__ by "my env variable value" and globalThis.__ANOTHER_ENV_VAR__ by "another env var value".

That's it. I hope it could help someone :)

Happy coding.

Top comments (0)