Environment variables in svelte + rollup

Viewed 4814

I'm looking for a straightforward way to set up environments. I.E. It would be great if I could run npm run dev:local and npm run dev:staging which load different environment files which are accessible at runtime via process.env. In understand it's compiled so I may have to access the variables in a different way. I'm using svelte with rollup straight from sveltejs/template. It should be simple but I see no way of doing it. It's cumbersome, but possible to do with webpack. Is there a simple way to do this?

1 Answers

You can inject build time constants in compiled code with @rollup/plugin-replace.

Something like this:

rollup.config.js

import replace from '@rollup/plugin-replace'
...

const production = !process.env.ROLLUP_WATCH

export default {
  ...
  plugins: [
    replace({
      'process.env': production ? '"production"' : '"dev"',
    }),
    ...
  ]
}

Note the double quotes of the value: '"production"'. The plugin injects the string as is in the code so, if you want a string, you need quotes in the quotes.

Also, as mentioned in the plugin's docs, it should be put at the beginning of your plugins array to enable optimizations like shaking out dead code by other plugins that follows it.

Related