Search code examples
javascriptsvelterollupjssvelte-3

Can't go into object defined by rollup plugin-replace


In a Svelte component, I'm trying to access an object I set up in my rollup config file. My rollup.config.js file looks like this:

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

...
export default {
...
    replace({
        foo: JSON.stringify({ bar: 'Hello' }),
    }),

...

In my Svelte component, a simple console.log(foo) works:

foo

But when I try to go into that foo object like console.log(foo.bar), I get foo is not defined:

fooUndefined


Solution

  • Good question! The object foo remains undefined so it is throwing the right error, and is unable to find foo to replace with whatever you are going to replace it with.

    The solution is having the replace plugin do its job. You may access your variable like this in your js or your .svelte files

    
    const { bar } = foo;
    
    console.log(bar);
    
    

    Note: there was a change made to this plugin check here for details. if you are planning to use environment variables using dotenv consider

    import { config } from "dotenv";
    
    ...
    replace({
          values: {
            foo: JSON.stringify({ bar: "Hello", ...config().parsed }),
          },
        }),
    ...
    

    and in your svelte file

      const { bar, ...rest } = foo;
      console.log("bar=>", bar);
      console.log("env=>", rest);