Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte framework: pass environment variables to client-side bundle at runtime

Posted this to the Svelte repo as well:

I just made my first Svelte app over the weekend, and really liked the experience. One thing I'm curious about, that I wasn't able to figure out with a decent amount of research, is if/how one could pass a runtime env var or similar to a client-side script so it's available in the bundle/browser. This probably isn't considered a "best practice", so maybe I'm just on my own here, but in Pug for example you can do something like the following (from a Hapi.js route handler for example):

  const context = {
    foo: bar,
    baz: ''
  }

  return h.view('index', context)

These vars are then available in the Pug context.

In my toy app I wanted to make it possible to pass an api key at server start time (either from a .env or CLI), and inject that from the Express server like so: app.use(express.static(`${__dirname}/public`)) and have that var be available in the client script. Again, it's probably not a best practice to be injecting api keys into client-side scripts and making calls from there, but is this kind of variable passing possible in Svelte?

It seems like this should be possible using either rollup-plugin-inject or rollup-plugin-replace, but I wasn't able to figure out how to make that work. This is definitely not a criticism of the framework, but perhaps a section on working with env vars would be a useful addition to the Svelte docs. Thanks!

like image 360
Blake Schwartz Avatar asked Apr 26 '18 16:04

Blake Schwartz


People also ask

What is $$ in svelte?

Note: Svelte uses the $: JavaScript label statement syntax to mark reactive statements. Just like the export keyword being used to declare props, this may look a little alien.


1 Answers

Typically this is the sort of thing you would do in your build config. From the rollupjs tag I'll assume you're using that — you could use rollup-plugin-replace to inject the content you need:

// rollup.config.js
import replace from 'rollup-plugin-replace';
import svelte from 'rollup-plugin-svelte';

export default {
  input: 'src/main.js',
  output: {
    file: 'public/bundle.js',
    format: 'iife'
  },
  plugins: [
    svelte(),
    replace({
      // you're right, you shouldn't be injecting this
      // into a client script :)
      'API_KEY': process.env.API_KEY
    })
  ]
};
like image 148
Rich Harris Avatar answered Sep 24 '22 02:09

Rich Harris