Skip to content

Theming #1550

@Rich-Harris

Description

@Rich-Harris

This question has come up enough times that we should probably come up with a solution — the question being 'how can I create a component kit (or similar) that supports theming?'.

One possible option would be to rely on CSS variables, but I think we can do better. The Svelteish way to tackle this would be to do it at compile-time. I propose something like this:

<!-- my-cool-component-kit/Widget.html -->
<div class="widget">
  <h1>{title}</h1>
</div>

<style>
  .widget {
    padding: $coolComponentKit.padding.normal;
  }

  h1 {
    color: $coolComponentKit.fgColor;
  }
</style>

The consumer of the component would then add something like this to their compiler options:

const { js } = svelte.compile(source, {
  variables: {
    coolComponentKit: {
      padding: {
        normal: '10px',
        larger: '20px'
      },
      fgColor: 'red'
    }
  }
});

Or, if the component library shipped a standard set of themes:

import * as themes from 'my-cool-component-kit/themes.js';

const { js } = svelte.compile(source, {
  variables: {
    coolComponentKit: themes.pastel
  }
});

Of course, we could do all this with preprocessors, which might be better as it doesn't lock us into a particular design:

import variables from 'svelte-preprocess-variables';
import * as themes from 'my-cool-component-kit/themes.js';

const { js } = svelte.compile(source, {
  preprocess: {
    style: variables({ coolComponentKit: themes.pastel })
  }
});

Now that I think about it, that might be preferable, if it was a 'blessed' approach that we could point people towards.

We might also consider supporting expressions:

<style>
  .foo {
    background-color: $(darken(coolComponentKit.colors.main, 0.5))
  }
</style>

Let's shave this yak! Any preferences for syntax? And should it be baked in or do we take the safer option of a preprocessor?

Also, as someone who doesn't really use component kits or CSS frameworks it's possible that I'm underestimating the problem — if you think this solution doesn't go far enough then please weigh in.

Metadata

Metadata

Assignees

No one assigned

    Labels

    awaiting submitterneeds a reproduction, or clarification

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions