sveltejs / rollup-plugin-svelte

Compile Svelte components with Rollup
MIT License
505 stars 79 forks source link

How to define global variables? #179

Closed pitaj closed 3 years ago

pitaj commented 3 years ago

I have a svelte component rendered within another app. That app defines some global variables which I'd like to use.

Whenever I use a custom variable (like config) I get a warning:

(!) Plugin svelte: 'config' is not defined
src/Customize.svelte
41: 
42: <svelte:head>
43:   <link rel="stylesheet" href={`${config.relative_path}/styles.css`} />
                                      ^
44: </svelte:head>
45: 

I cannot, for the life of me, find a way to add known global variables to avoid the warning.

I know I could provide onwarn but that seems hacky and would suppress warnings for actual issues.

lukeed commented 3 years ago

I think you can silence the warning by using window.config

Otherwise, you have to use onwarn, as you mentioned. But you can use it to filter away messages containing config so that you still see other warnings.

pitaj commented 3 years ago

I implemented a workaround using onwarn. I think this would be a nice feature for those of us integrating within an existing codebase, though I suppose there's also the option of using rollup globals and importing as modules instead.

const globalVars = new Set([
  'config',
]);

export default {
  ...
  plugins: [
    svelte({
      ...
      onwarn(warning, handler) {
        if (warning.code === 'missing-declaration') {
          const name = warning.message.split("'")[1];
          if (globalVars.has(name)) {
            return;
          }
        }

        handler(warning);
      },
    }),
  ],
  ...
};
lukeed commented 3 years ago

It's not a workaround. This is what the option hook is meant for

pitaj commented 3 years ago

Compared to an option like so:

  plugins: [
    svelte({
      ...
      globals: [
        'config'
      ]
    }),
  ],

I'd say it's a workaround.

lukeed commented 3 years ago

I believe the term you're looking for is "feature request"

pitaj commented 3 years ago

To be clear, I came into this thinking I had just missed something. Yes this would be a feature request, and probably one to actually apply to the svelte compiler, not the rollup plugin. I understand that the code I gave is currently the suggested solution, but given that many other tools (typescript, eslint, etc) have this ability, it isn't ideal for supporting global vars.

I'll close this because rollup global imports is probably a better solution, and because this feature would need to be implemented in the svelte compiler. At least other people will now have an answer if they go looking.