Skip to content Skip to sidebar Skip to footer

Environment Variables In Svelte + Rollup

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

Solution 1:

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_WATCHexportdefault {
  ...
  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.

Post a Comment for "Environment Variables In Svelte + Rollup"