Installing Material Web Components for use in a Sveltekit Application
I recently switched this website from IBM's Carbon design system to the Material UI web components library. Carbon was appealing for it's solid support and a Svelte-specific library, but I found its corporate aesthetic felt somewhat rigid, with limited customization options.
Finding component libraries that support svelte natively can still be difficult. The appeal of web components lies in their portability. In theory, since Material UI's components use native browser APIs, they should integrate seamlessly with any framework—including Svelte. However, following the official Material Components setup documentation alone wasn't enough to get them working in my SvelteKit application.
After some debugging (and helpful assistance from Claude), I successfully implemented the components. I'm sharing these steps for anyone else who might encounter similar setup challenges.
Rendering Material Web Components in a Sveltekit Application
1. Install the necessary dependencies
npm install @material/web
2. For TypeScript support, you'll need to modify your app.d.ts
or create a new declaration file to handle the custom elements.
/// <reference types="@material/web/select/select.js" />
/// <reference types="@material/web/button/button.js" />
// Add other components you plan to use
``
3. Set up the components in your SvelteKit app.
Create a new file `src/lib/material.ts
// src/lib/material.ts
import '@material/web/button/filled-button.js';
import '@material/web/button/outlined-button.js';
import '@material/web/textfield/filled-text-field.js';
// Import other components as needed
4. To ensure proper TypeScript support, update your tsconfig.json
:
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"moduleResolution": "node",
"target": "es2020",
"allowSyntheticDefaultImports": true,
"strict": true,
"customElements": true
}
}
5. Import the components in your src/routes/+layout.svelte
:
<script lang="ts">
import '../lib/material';
</script>
<slot />
Now you can render the web components in any Svelte component:
<script lang="ts">
let value = '';
</script>
<md-filled-button>Click me</md-filled-button>
<md-filled-text-field
label="Username"
></md-filled-text-field>