How do I import a Material Web Component in SvelteKit?

Viewed 1050

I followed the standard tutorial in sveltkit to create a Typescript Project for a basic template.

I wanted to use Material Web Component Button.

I npm install @material/mwc-button.

Then I simply add the following to routes/index.svelte

<script>
    import "@material/mwc-button";
</script>

To which I get SyntaxError: Cannot use import statement outside a module.

This is driving me crazy as it's step one of my requirement and this is week 3 of being stuck. I don't know even where to start. Is this a vite problem, sveltekit problem, mwc problem? Any advice would be amazing.

1 Answers

Wow, that error message is very unhelpful. In a non-TS SvelteKit project, you get Error when evaluating SSR module /node_modules/lit-html/lib/template-result.js: ReferenceError: window is not defined, which is a little clearer about what is going on.

Importing Material Web Components runs code that uses window, which is not available on the server. Because of this, Vite throws an error while trying to process the imported mwc-button library. You can use a dynamic import in Svelte's onMount lifecycle function so that the library is only imported on the client. You will have to do this with any web component you import.

<script>
    import { onMount} from 'svelte';
    onMount(async () => {
        await import('@material/mwc-button');
    })
</script>

<mwc-button>Button</mwc-button>

For further reference, see the "How do I use a client-side only library that depends on document or window?" question in the SvelteKit FAQ.

Related